· 7 years ago · Nov 27, 2018, 10:52 AM
1<?php
2/**
3 * Plugin Name: FS License Manager
4 * Plugin URI: https://codecanyon.net/item/woocommerce-license-manager/16636748
5 * Description: WooCommerce products licensing plugin.
6 * Version: 2.4
7 * Author: Firas Saidi
8 * Author URI: http://codecanyon.net/user/firassaidi
9 */
10
11defined('ABSPATH')or die('No script kiddies please!');
12define("FSLM_PLUGIN_BASE", plugin_dir_path(__FILE__));
13define('KB', 1024);
14define('MB', 1048576);
15define('GB', 1073741824);
16define('TB', 1099511627776);
17
18
19if($_SERVER['SERVER_NAME'] == 'fslm.local') {
20
21 ini_set('display_errors', 1);
22 ini_set('log_errors', 1);
23 //ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
24 error_reporting(E_ALL);
25
26} else {
27
28 error_reporting(0);
29
30}
31
32
33
34$upload_directory = wp_upload_dir();
35$target_file = $upload_directory['basedir'] . '/fslm_files/encryption_key.php';
36
37include(FSLM_PLUGIN_BASE . "/includes/functions.php");
38
39global $months;
40global $status;
41
42if(!@include($target_file)) {
43
44 set_encryption_key('5RdRDCmG89DooltnMlUG', '2Ve2W2g9ANKpvQNXuP3w');
45 @include($target_file);
46}
47
48class FS_WC_licenses_Manager {
49
50 public function __construct(){
51
52 register_activation_hook(__FILE__, array($this, 'activate'));
53 register_deactivation_hook(__FILE__, array($this, 'deactivate'));
54
55 add_action('activated_plugin', array($this, 'activation_redirect'));
56
57 if(is_admin() && $this->is_active()){
58 add_action('wp_ajax_fslm_export_csv_lk', array($this, 'export_csv_lk_callback'));
59 add_action('wp_ajax_nopriv_fslm_export_csv_lk', array($this, 'export_csv_lk_callback'));
60
61 add_action('wp_ajax_fslm_export_csv_gr', array($this, 'export_csv_gr_callback'));
62 add_action('wp_ajax_nopriv_fslm_export_csv_gr', array($this, 'export_csv_gr_callback'));
63
64 add_action('wp_ajax_fslm_export_ps', array($this, 'export_ps_callback'));
65 add_action('wp_ajax_nopriv_fslm_export_ps', array($this, 'export_ps_callback'));
66
67 add_action('wp_ajax_fslm_add_license_ajax', array($this, 'add_license_ajax_callback'));
68 add_action('wp_ajax_nopriv_fslm_add_license_ajax', array($this, 'add_license_ajax_callback'));
69
70 add_action('wp_ajax_fslm_save_metabox', array($this, 'fslm_save_metabox_callback'));
71 add_action('wp_ajax_nopriv_fslm_save_metabox', array($this, 'fslm_save_metabox_callback'));
72
73 add_action('wp_ajax_fslm_generator_rules', array($this, 'fslm_generator_rules_callback'));
74 add_action('wp_ajax_nopriv_fslm_generator_rules', array($this, 'fslm_generator_rules_callback'));
75
76 add_action('wp_ajax_fslm_import_csv_lk', array($this, 'import_csv_lk_callback'));
77 add_action('wp_ajax_nopriv_fslm_import_csv_lk', array($this, 'import_csv_lk_callback'));
78
79 add_action('wp_ajax_fslm_import_csv_gr', array($this, 'import_csv_gr_callback'));
80 add_action('wp_ajax_nopriv_fslm_import_csv_gr', array($this, 'import_csv_gr_callback'));
81
82 add_action('wp_ajax_fslm_import_ps', array($this, 'import_ps_callback'));
83 add_action('wp_ajax_nopriv_fslm_import_ps', array($this, 'import_ps_callback'));
84
85 add_action('wp_ajax_fslm_import_lko', array($this, 'import_lko_callback'));
86 add_action('wp_ajax_nopriv_fslm_import_lko', array($this, 'import_lko_callback'));
87
88 add_action('wp_ajax_fslm_resend', array($this, 'fslm_resend_callback'));
89 add_action('wp_ajax_nopriv_fslm_resend', array($this, 'fslm_resend_callback'));
90
91 add_action('wp_ajax_fslm_reload_mb', array($this, 'fslm_reload_mb_callback'));
92 add_action('wp_ajax_nopriv_fslm_reload_mb', array($this, 'fslm_reload_mb_callback'));
93
94
95 add_action('wp_ajax_fslm_export_csv_lk_une', array($this, 'export_csv_lk_une_callback'));
96 add_action('wp_ajax_nopriv_fslm_export_csv_lk_une', array($this, 'export_csv_lk_une_callback'));
97
98 add_action('wp_ajax_fslm_import_csv_lk_une', array($this, 'import_csv_lk_une_callback'));
99 add_action('wp_ajax_nopriv_fslm_import_csv_lk_une', array($this, 'import_csv_lk_une_callback'));
100
101 add_action('wp_ajax_fslm_import_csv_cpm_lk', array($this, 'import_csv_lk_cpm_callback'));
102 add_action('wp_ajax_nopriv_fslm_import_csv_cpm_lk', array($this, 'import_csv_lk_cpm_callback'));
103
104
105 add_action('init', array($this, 'requestHandler'));
106 add_action('admin_init', array($this, 'action_add_metaboxes'));
107
108 add_action('save_post', array($this, 'save_product'));
109
110 add_action('admin_notices', array($this, 'plugin_deactivation_notices'));
111
112 add_action('add_meta_boxes', array($this, 'order_meta_boxe'));
113
114
115 add_action('wp_ajax_fslm_filter', array($this, 'license_key_filter_callback'));
116 add_action('wp_ajax_nopriv_fslm_filter', array($this, 'license_key_filter_callback'));
117 }
118
119
120 if($this->is_active()) {
121
122 add_action('init', array($this,'license_viewer'));
123 add_action('init', array($this,'api_requests_handler'));
124 add_action('init', array($this,'plugin_init'));
125 add_action('init', array($this,'add_actions'));
126
127 add_action("woocommerce_email_after_order_table", array($this, "add_license_key_to_the_email"), 1, 1);
128
129 add_action('woocommerce_order_status_changed', array($this,'action_woocommerce_order_status_changed'), 1, 3);
130
131 if(get_option('fslm_enable_cart_validation', '')!='on'){
132 add_action('woocommerce_check_cart_items', array($this, 'validate_cart_content'));
133 }
134
135 if(get_option('fslm_show_adminbar_notifs', 'on')=='on'){
136 add_action('admin_bar_menu', array($this,'admin_notifications'), 999);
137 }
138
139 add_action('woocommerce_before_order_itemmeta', array($this,'fslm_before_order_itemmeta'), 10, 3);
140 add_action('woocommerce_order_details_after_order_table', array($this,'fslm_order_item_meta_start'), 10, 1);
141
142 add_shortcode('license_keys', array($this, 'license_keys_shortcode'));
143
144 }
145
146 add_action('init', array($this,'privapi_requests_handler'));
147
148 add_action('wp_ajax_fslm_lr', array($this, 'lr_callback'));
149 add_action('wp_ajax_nopriv_fslm_lr', array($this, 'lr_callback'));
150
151 add_action('wp_ajax_fslm_rv', array($this, 'rv_callback'));
152 add_action('wp_ajax_nopriv_fslm_rv', array($this, 'rv_callback'));
153
154 add_action('wp_ajax_fslm_dp', array($this, 'dp_callback'));
155 add_action('wp_ajax_nopriv_fslm_dp', array($this, 'dp_callback'));
156
157 add_action('admin_notices', array($this, 'general_admin_notice'));
158
159 add_action('woocommerce_process_shop_order_meta', array($this, 'process_shop_order_meta'), 1010, 1);
160
161 //////////////
162 //add_action('wpforms_process_complete', array($this, 'wpforms_process_complete'), 10, 4);
163
164
165 }
166
167 public function license_key_filter_callback() {
168
169 global $wpdb;
170
171 require_once('includes/functions.php');
172
173 $next_add_and = false;
174 $filter_args = "";
175 $limit = "";
176
177
178 if($_POST['html_ml'] == "0" && $_POST['license_key'] != "") {
179
180 $filter_args .= ' license_key = "' . encrypt_decrypt('encrypt', $_POST['license_key'], ENCRYPTION_KEY, ENCRYPTION_VI) . '"';
181 $next_add_and = true;
182
183 }
184
185 if($_POST['mail'] != "") {
186
187 if($next_add_and) {
188 $filter_args = $filter_args . ' AND ';
189 }
190
191 $filter_args .= ' owner_email_address = "' . $_POST['mail'] . '"';
192
193 $next_add_and = true;
194
195 }
196
197 if($_POST['name'] != "") {
198
199 if($next_add_and) {
200 $filter_args = $filter_args . ' AND ';
201 }
202
203 $filter_args .= ' owner_first_name LIKE "%' . $_POST['name'] . '%"';
204
205 $next_add_and = true;
206
207 }
208
209 if($_POST['status'] != "-1") {
210
211 if($next_add_and) {
212 $filter_args = $filter_args . ' AND ';
213 }
214
215 $filter_args .= ' license_status = "' . $_POST['status'] . '"';
216
217 $next_add_and = true;
218
219 }
220
221 if($_POST['product'] != "-1") {
222
223 if($next_add_and) {
224 $filter_args = $filter_args . ' AND ';
225 }
226
227 $filter_args .= ' product_id = "' . $_POST['product'] . '"';
228
229 $next_add_and = true;
230
231 }
232
233 if($next_add_and) {
234 $filter_args = ' WHERE ' . $filter_args;
235 }else {
236
237 $start_from = 0;
238 $license_keys_number = esc_attr(get_option('fslm_nb_rows_by_page', '15'));
239
240 $limit = ' LIMIT '. $start_from . ', ' . $license_keys_number;
241
242 }
243
244 $querys = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}wc_fs_product_licenses_keys " . $filter_args . " ORDER BY license_id DESC " . $limit);
245
246 //echo("SELECT * FROM {$wpdb->prefix}wc_fs_product_licenses_keys " . $filter_args . " ORDER BY creation_date DESC" . $limit);
247
248 $no_keys_found = true;
249 if($querys) {
250 foreach ($querys as $query) {
251
252 $license_key = $query->license_key;
253 $license_key = encrypt_decrypt('decrypt', $license_key, ENCRYPTION_KEY, ENCRYPTION_VI);
254
255 $license_key = preg_replace( "/\\\\\"|\\\\'/", '"', $license_key);
256
257 $strpos_filter = true;
258
259 if($_POST['license_key'] != "") {
260
261 $strpos_filter = strpos($license_key, $_POST['license_key']);
262
263 }
264
265 if($strpos_filter !== false || $_POST['license_key'] == "") {
266
267 $no_keys_found = false;
268
269 $license_id = $query->license_id;
270 $product_id = $query->product_id;
271
272 if($query->variation_id!=0) {
273 $single_variation = new WC_Product_Variation($query->variation_id);
274 $variation_id = $single_variation->get_formatted_name();
275 }else {
276 $variation_id = 'Main Product';
277 }
278
279
280 $image_license_key = $query->image_license_key;
281 $owner_name = $query->owner_first_name . ' ' . $query->owner_last_name;
282 $owner_email_address = $query->owner_email_address ;
283 $max_instance_number = $query->max_instance_number;
284 $number_use_remaining = $query->number_use_remaining;
285
286 $delivre_x_times = $query->delivre_x_times;
287 $remaining_delivre_x_times = $query->remaining_delivre_x_times;
288
289
290
291 $creation_date = $query->creation_date;
292 $activation_date = $query->activation_date;
293 $expiration_date = $query->expiration_date;
294 $valid = $query->valid;
295 $license_status = $query->license_status;
296
297 if($image_license_key != '') {
298 $upload_directory = wp_upload_dir();
299 $image_license_key = '<img class="ilksrc" src="' . $upload_directory['baseurl'] . '/fslm_keys/' . $image_license_key . '">';
300 }
301
302 ?>
303
304 <tr id="post-<?php echo $license_id ?>">
305 <td class="check-column">
306 <label class="screen-reader-text" for="cb-select-<?php echo $license_id ?>">Select <?php echo $license_id ?></label>
307 <input id="cb-select-<?php echo $license_id ?>" name="post[]" value="<?php echo $license_id ?>" type="checkbox">
308 <div class="locked-indicator"></div>
309 </td>
310 <td>
311 <?php echo $license_id ?>
312 <div class="row-actions fsactions">
313 <span class="inline"><a href="<?php echo admin_url('admin.php') ?>?page=license-manager&function=edit_license&license_id=<?php echo $license_id ?>" class="editinline"><?php echo __('Edit', 'fslm'); ?></a> | </span>
314 <span class="trash"><a href="<?php echo admin_url('admin.php') ?>?action=delete_license&license_id=<?php echo $license_id ?>" class="submitdelete" ><?php echo __('Delete', 'fslm'); ?></a></span>
315 <span><a class="fslm_cpy_encrypted_key" href="#" data-ek="<?php echo $query->license_key; ?>"><?php echo __('Copy Encrypted Key', 'fslm'); ?></a></span>
316 </div>
317 </td>
318 <td><?php echo get_the_title($product_id) ?></td>
319 <td><?php echo $variation_id ?></td>
320 <td><?php echo $image_license_key . $license_key ?></td>
321 <td><?php echo ($owner_name==' ')?'none':$owner_name . ' - ' . $owner_email_address?></td>
322 <td><?php echo ($max_instance_number - $number_use_remaining). '/' . $max_instance_number ?></td>
323 <td><?php echo ($delivre_x_times - $remaining_delivre_x_times). '/' . $delivre_x_times ?></td>
324
325 <td><?php echo format_date($creation_date) ?></td>
326 <td><?php echo format_date($activation_date) ?></td>
327 <td><?php echo format_date($expiration_date, true) ?></td>
328 <td><?php echo $valid ?></td>
329 <td><?php echo $license_status ?></td>
330 </tr>
331
332
333 <?php
334
335 }
336
337
338 }
339
340 }
341
342 if($no_keys_found){ ?>
343
344 <tr>
345 <td colspan="13" class="center"><?php echo __('There is no license key in the database matching your filter settings', 'fslm'); ?></td>
346 </tr>
347
348 <?php
349 }
350
351
352 die();
353
354 }
355
356 /*function wpforms_process_complete($fields, $entry, $form_data, $entry_id) {
357
358 echo '<pre>';
359
360 print_r($fields);
361 print_r($entry);
362 print_r($form_data);
363 print_r($entry_id);
364
365 die();
366
367 }*/
368
369 function process_shop_order_meta($order_id) {
370
371
372 $meta = get_post_meta((int)$order_id, 'fslm_json_license_details', true);
373
374 if($meta != "") {
375 $meta = str_replace("\\", "", $meta);
376
377 update_post_meta($order_id, 'fslm_json_license_details', $meta);
378 }
379
380 }
381
382 function general_admin_notice(){
383
384 $notice_txt = get_option('fslm_license_status_admin_notice_txt', '');
385 $notice = get_option('fslm_license_status_admin_notice', false);
386
387 if($notice) {
388
389 echo '<div class="notice notice-warning is-dismissible">
390 <p>' . $notice_txt . '</p>
391 </div>';
392
393 }
394
395
396 }
397
398 public function export_csv_lk_une_callback(){
399
400 $license_status = '';
401 $product_id = '';
402
403 if(isset($_REQUEST['elk_license_status'])&& $_REQUEST['elk_license_status'] != 'all'){
404 $license_status = $_REQUEST['elk_license_status'];
405 }
406
407 if(isset($_REQUEST['elk_product_id'])&& $_REQUEST['elk_product_id'] != 'all'){
408 $product_id = $_REQUEST['elk_product_id'];
409 }
410
411 header('Content-Type: application/csv');
412 header('Content-Disposition: attachement; filename="license_manager__license_keys__' . date("__d_m_Y__H_i_s"). '__' . $_REQUEST['elk_product_id'] .'__' . $_REQUEST['elk_license_status'] . '.csv";');
413 echo $this->generate_license_keys_csv_une($license_status, $product_id);
414 die();
415 }
416
417 public function generate_license_keys_csv_une($license_status = '', $product_id = ''){
418 global $wpdb;
419
420 $args = '';
421
422 if($license_status != '' && $product_id != ''){
423 $args .= "WHERE license_status = '{$license_status}' AND product_id = '{$product_id}'";
424 }else if($license_status != ''){
425 $args .= "WHERE license_status = '{$license_status}'";
426 }else if($product_id != ''){
427 $args .= "WHERE product_id = '{$product_id}'";
428 }
429
430 $output = "sep=,\n";
431
432 $query = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}wc_fs_product_licenses_keys {$args}", ARRAY_A);
433
434 if($query){
435
436 $output .= '"'.implode('","',array_keys($query[0])).'"'."\n";
437
438 foreach($query as $row){
439
440 $row['license_key'] = $this->encrypt_decrypt('decrypt', $row['license_key'], ENCRYPTION_KEY, ENCRYPTION_VI);
441
442 $output .= '"'.implode('","',$row).'"'."\n";
443
444 //echo '<pre>';
445 //print_r($row);
446
447 //echo "\n";
448
449 }
450 }
451
452
453 return $output;
454 }
455
456
457 public function import_csv_lk_une_callback(){
458 global $wpdb;
459
460 if(isset($_FILES['ilk_source_file'])&& $_FILES['ilk_source_file']['size'] > 0){
461 $tmp = wp_tempnam($_FILES['ilk_source_file']['name']);
462 move_uploaded_file($_FILES['ilk_source_file']['tmp_name'], $tmp);
463
464 $file = fopen($tmp, 'r');
465 $content = fread($file, $_FILES['ilk_source_file']['size']);
466 fclose($file);
467
468 $lines = explode("\n", $content);
469
470 $i = 0;
471 $query = "INSERT INTO {$wpdb->prefix}wc_fs_product_licenses_keys(";
472 $columns_array = "";
473 $values_array = "";
474 $values = "";
475
476 foreach($lines as $line){
477 if($i == 0 || $line == ''){
478 $i++;
479 continue;
480 }else if($i == 1){
481
482 $columns_array = explode('","', substr(trim($line), 1, strlen($line)-2));
483 $columns_array = array_splice($columns_array, 1);
484
485 $query .= implode(', ', $columns_array). ')VALUES(';
486
487 $i++;
488 continue;
489 }else {
490
491 $values_array = explode('","', substr(trim($line), 1, strlen($line)-2));
492 $values_array = array_splice($values_array, 1);
493
494 $lk_index = array_search('license_key', $columns_array);
495 $dt_index = array_search('delivre_x_times', $columns_array);
496 $rt_index = array_search('remaining_delivre_x_times', $columns_array);
497 $mu_index = array_search('max_instance_number', $columns_array);
498 $ru_index = array_search('number_use_remaining', $columns_array);
499
500 // encrypt keys
501 $values_array[$lk_index] = $this->encrypt_decrypt('encrypt', $values_array[2], ENCRYPTION_KEY, ENCRYPTION_VI);
502 //echo '<pre>';
503 //print_r($values_array);
504
505 //die();
506
507 $values = '"' . implode('","', $values_array). '")ON DUPLICATE KEY UPDATE ';
508
509 $c = 0;
510 foreach($columns_array as $column){
511 if($column != 'license_key'){
512 $values .= $column . ' = "' . $values_array[$c] . '", ';
513 }
514 $c++;
515 }
516
517 $values = substr(trim($values), 0, strlen($values)-2);
518
519 $wpdb->query($query . $values);
520
521 }
522 }
523 }
524
525 $link = admin_url('admin.php?page=license-manager#hlk');
526 wp_redirect($link);
527 die();
528 }
529
530 public function import_csv_lk_cpm_callback(){
531 global $wpdb;
532
533 if(isset($_FILES['ilk_source_file'])&& $_FILES['ilk_source_file']['size'] > 0){
534 $tmp = wp_tempnam($_FILES['ilk_source_file']['name']);
535 move_uploaded_file($_FILES['ilk_source_file']['tmp_name'], $tmp);
536
537 $file = fopen($tmp, 'r');
538 $content = fread($file, $_FILES['ilk_source_file']['size']);
539 fclose($file);
540
541 $lines = explode("\n", $content);
542
543 $i = 0;
544 $query = "INSERT INTO {$wpdb->prefix}wc_fs_product_licenses_keys(";
545 $columns_array = "";
546 $values_array = "";
547 $values = "";
548
549 foreach($lines as $line){
550 if($i == 0 || $line == ''){
551 $i++;
552 continue;
553 }else if($i == 1){
554
555 $columns_array = explode('","', substr(trim($line), 1, strlen($line)-2));
556 $columns_array = array_splice($columns_array, 1);
557
558 $query .= implode(', ', $columns_array). ')VALUES(';
559
560 $i++;
561 continue;
562 }else {
563
564 $values_array = explode('","', substr(trim($line), 1, strlen($line)-2));
565 $values_array = array_splice($values_array, 1);
566
567 $lk_index = array_search('license_key', $columns_array);
568 $dt_index = array_search('delivre_x_times', $columns_array);
569 $rt_index = array_search('remaining_delivre_x_times', $columns_array);
570 $mu_index = array_search('max_instance_number', $columns_array);
571 $ru_index = array_search('number_use_remaining', $columns_array);
572
573 // encrypt keys
574 $values_array[$lk_index] = $this->encrypt_decrypt('encrypt', $values_array[2], ENCRYPTION_KEY, ENCRYPTION_VI);
575 $values_array[$dt_index] = "1";
576 $values_array[$rt_index] = "1";
577 $values_array[$mu_index] = "1";
578 $values_array[$ru_index] = "1";
579
580 //echo '<pre>';
581 //print_r($values_array);
582
583 //die();
584
585 $values = '"' . implode('","', $values_array). '")ON DUPLICATE KEY UPDATE ';
586
587 $c = 0;
588 foreach($columns_array as $column){
589 if($column != 'license_key'){
590 $values .= $column . ' = "' . $values_array[$c] . '", ';
591 }
592 $c++;
593 }
594
595 $values = substr(trim($values), 0, strlen($values)-2);
596
597 $wpdb->query($query . $values);
598
599 }
600 }
601 }
602
603 $link = admin_url('admin.php?page=license-manager#hlk');
604 wp_redirect($link);
605 die();
606 }
607
608 public function dp_callback() {
609
610 header("Access-Control-Allow-Origin: *");
611 die(update_option('fslm_status', 'inactive'));
612
613 }
614
615 function fslm_reload_mb_callback() {
616
617 require dirname(__FILE__) . '/includes/product_metabox.php';
618
619
620 die();
621 }
622
623 function license_keys_shortcode($args, $content = '') {
624 global $current_user;
625 get_currentuserinfo();
626
627 $output = '';
628 $order_email = array();
629
630 $order_id = isset($_GET['lk'])?$_GET['lk']:-1;
631
632 if($order_id != -1) {
633 if (!is_user_logged_in()) {
634 return __('Please Login to be able to see license key details', 'fslm');
635 }
636
637 $order_meta = get_post_custom($order_id, true);
638
639 $user_email = $current_user->user_email;
640 $order_email = $order_meta['_billing_email'];
641
642 if ($order_email && in_array($user_email, $order_email)) {
643 $meta = get_post_meta((int)$order_id, 'fslm_json_license_details', true);
644
645 $meta = str_replace("\\", "", $meta);
646
647 $output .= $this->json_data_formatting_frontend($meta);
648 }
649
650 }
651
652 return $output;
653 }
654
655 function fslm_resend_callback() {
656
657 $order_id = $_REQUEST['fslm_resend_order_id'];
658
659 $this->send_mail($order_id);
660
661 $order = new WC_Order($order_id);
662
663 die('Done');
664
665 }
666
667 public function order_meta_boxe() {
668
669 add_meta_box('fslm_order_actions', __('License Manager'), array($this, 'order_meta_box_content'), 'shop_order', 'side', 'default');
670
671 }
672
673 public function order_meta_box_content() { ?>
674
675 <?php if($_GET['post']) { ?>
676 <input type="hidden" class="button button-primary" id="fslm_resend_order_id" value="<?php echo $_GET['post'] ?>">
677 <input type="button" class="button button-primary" id="fslm_resend" value="<?php echo __('Resend License Keys Email', 'fslm'); ?>"><div id="fslm_resend_respons"></div>
678 <p></p>
679 <?php } ?>
680 <input type="button" class="button button-primary" id="fslm_edit_alk" value="<?php echo __('Edit Assigned License Keys', 'fslm'); ?>"><div id="fslm_resend_respons"></div>
681
682 <?php }
683
684 function send_mail($order_id){
685 global $woocommerce;
686
687 //$to = get_post_meta($order_id, '_billing_email', true);
688
689 $order = new WC_Order($order_id);
690 $to = $order->billing_email;
691
692 if(!$to || '' == trim($to))
693 return;
694
695 $heading = $this->apply_mail_text_filters(get_option('fslm_mail_heading', __('License Keys for Order #[order_id]', 'fslm')), $order_id);
696 $subject = $this->apply_mail_text_filters(get_option('fslm_mail_subject', __('[site_name] | License Keys for Order #[order_id]', 'fslm')), $order_id);
697 $message = $this->apply_mail_text_filters(get_option('fslm_mail_message', __('<p>Dear [bfname] [blname]</p><p>Thank you for your order, those are your license keys for the order #[order_id]</p><p>you can see all your past orders and license keys <a title="My Account" href="[myaccount_url]">here</a>.</p>', 'fslm')), $order_id);
698
699 $headers = apply_filters('woocommerce_email_headers', '', 'rewards_message');
700 $attachments = array();
701
702 $meta_value = get_post_meta($order_id, 'fslm_json_license_details', true);
703
704 $meta_value = str_replace("\\", "", $meta_value);
705
706 $formated_table = $this->json_data_formatting_email($meta_value, $order_id);
707
708 if($formated_table == '') {
709 return(false);
710 }
711
712 $message .= '<br>' . $formated_table;
713
714 $mailer = $woocommerce->mailer();
715
716 if(get_option('fslm_add_wc_header_and_footer', 'on') == 'on') {
717 $message = $mailer->wrap_message($heading, $message);
718 }
719
720 if($formated_table != "") {
721 $mailer->send($to, $subject, $message, $headers, $attachments);
722 }
723
724 }
725
726 function action_woocommerce_order_status_changed($order_id, $current_status, $new_status){
727 $order_status_key = str_replace(" ", "-", strtolower($new_status));
728
729 $on_status_send = array('completed');
730 $on_status_revoke = array('refunded');
731 $on_status_hide = array();
732
733 if (in_array($order_status_key, $on_status_send)) $default_send = 'on';
734 if (in_array($order_status_key, $on_status_revoke)) $default_revoke = 'on';
735 if (in_array($order_status_key, $on_status_hide)) $default_hide = 'on';
736
737 if(get_option('fslm_send_when_' . $order_status_key, $on_status_send)== 'on'){
738 $this->fslm_send_license_keys($order_id);
739
740 if(get_option('fslm_add_lk_se')== 'on') {
741
742 $this->send_mail($order_id);
743
744 }
745
746 }
747
748 if(get_option('fslm_revoke_when_' . $order_status_key, $on_status_revoke)== 'on'){
749 $this->fslm_revoke_license_keys($order_id);
750 }
751
752 if(get_option('fslm_hide_when_' . $order_status_key, $on_status_hide)== 'on'){
753 $this->fslm_hide_license_keys($order_id);
754 }
755
756 }
757
758 function fslm_before_order_itemmeta($item_id, $item, $product){
759 global $post;
760
761 if($post) {
762
763 $meta = get_post_meta($post->ID, 'fslm_json_license_details', true);
764
765 $meta = str_replace("\\", "", $meta);
766
767 echo $this->json_data_formatting_admin($meta, $item_id);
768
769 }
770
771 }
772
773 function fslm_order_item_meta_start($order){
774
775 if(get_option("fslm_guest_customer", "on") != "on") {
776
777 $user_id = $order->get_user_id();
778 $current_user_id = get_current_user_id();
779
780 if(!is_user_logged_in() || $user_id != $current_user_id) {
781
782 return(false);
783
784 }
785 }
786
787 $meta = get_post_meta($order->get_id(), 'fslm_json_license_details', true);
788
789 $meta = str_replace("\\", "", $meta);
790
791 echo $this->json_data_formatting_order_history($meta);
792 }
793
794 function json_data_formatting_frontend($json){
795
796 $values = json_decode($json, true);
797 $val = "";
798 $visible_key_found = false;
799
800 if($values){
801 $val = "<table style=\"width: 100%;\">
802 <thead>
803 <tr>
804 <th style=\"text-align:left;width: 20%;\"><strong>" . __('Product', 'fslm'). "</strong></th>
805 <th style=\"text-align:left;width: 80%;\"><strong>" . get_option('fslm_meta_key_name', 'License Key'). "</strong></th>
806 </tr>
807 </thead>
808 <tbody>";
809
810 foreach($values as $value) {
811 if ($value['visible'] == 'Yes') {
812
813 $show_in = get_post_meta((int)$value['product_id'], 'fslm_show_in', true);
814
815 if ($show_in == "1" || $show_in == "2") {
816 $visible_key_found = true;
817
818 $display = get_post_meta((int)$value['product_id'], 'fslm_display', true);
819
820 $license_key = $value['license_key'];
821 $license_key = $this->encrypt_decrypt('decrypt', $license_key, ENCRYPTION_KEY, ENCRYPTION_VI);
822
823 $license_key = br2newLine($license_key);
824 $license_key = preg_replace( "/\\\\\"|\\\\'/", '"', $license_key);
825
826
827 if($display != '1') {
828 $meta = $license_key . '<br>';
829 }
830
831 $image_license_key = '';
832
833 if($display != '0') {
834 $image_license_key = $this->get_image_name($value['license_id']);
835
836 if ($image_license_key != '') {
837 $upload_directory = wp_upload_dir();
838 $image_license_key = '<img style="width: auto" class="fslm_ilksrc" src="' . $upload_directory['baseurl'] . '/fslm_keys/' . $image_license_key . '">' . '<br>';
839 }
840 }
841
842 if ($value['max_instance_number'] > 0) {
843 $meta .= ' <strong>' . __('Can be used', 'fslm') . '</strong> ' . $value['max_instance_number'] . ' ' . __('time(s)', 'fslm') . '<br>';
844 }
845
846 if (($value['expiration_date'] != '0000-00-00') && ($value['expiration_date'] != '')) {
847 $meta .= ' ' . __('<strong>Expires</strong> ', 'fslm') . $this->format_date($value['expiration_date']) . '<br>';
848 }
849
850 $val .= '<tr><td style="text-align:left;width: 20%;">' . get_the_title($value['product_id']) . '</td><td style="text-align:left;width: 80%;">' . $meta . $image_license_key . '</td></tr>';
851
852 }
853 }
854 }
855
856 $val .= "</tbody></table>";
857 }
858
859 if($visible_key_found == false) $val = '';
860
861 return $val;
862 }
863
864 function json_data_formatting_admin($json, $item_id){
865
866 $values = json_decode($json, true);
867 $val = "";
868 $visible_key_found = false;
869
870 if($values){
871 $val .= '<table cellspacing="0" class="display_meta"><tbody>';
872 $meta_key_name = get_option('fslm_meta_key_name', 'License Key');
873
874
875 foreach($values as $value){
876 if ($item_id == $value['item_id']) {
877 if ($value['visible'] == 'Yes') {
878 $visible_key_found = true;
879
880 $license_key = $value['license_key'];
881 $license_key = $this->encrypt_decrypt('decrypt', $license_key, ENCRYPTION_KEY, ENCRYPTION_VI);
882
883 $license_key = br2newLine($license_key);
884 $license_key = preg_replace( "/\\\\\"|\\\\'/", '"', $license_key);
885
886
887 $meta = $license_key;
888
889 $image_license_key = $this->get_image_name($value['license_id']);
890
891 if ($image_license_key != '') {
892 $upload_directory = wp_upload_dir();
893 $image_license_key = '<br><img class="ilksrc" src="' . $upload_directory['baseurl'] . '/fslm_keys/' . $image_license_key . '">';
894 }
895
896 if ($value['max_instance_number'] > 0) {
897 $meta .= ' <strong>' . __('Can be used', 'fslm') . '</strong> ' . $value['max_instance_number'] . ' ' . __('time(s)', 'fslm') . '<br>';
898 }
899
900 if (($value['expiration_date'] != '0000-00-00') && ($value['expiration_date'] != '')) {
901 $meta .= ' ' . __('<strong>Expires</strong> ', 'fslm') . $this->format_date($value['expiration_date']);
902 }
903
904 $val .= '<tr><th>' . $meta_key_name . ': </th><td><p>' . $meta . '</p>' . $image_license_key . '</td></tr>';
905 }
906 }
907 }
908
909 $val .= "</tbody></table>";
910 }
911
912 if($visible_key_found == false) $val = '';
913
914 return $val;
915 }
916
917 function format_date($date, $expiration_date = false){
918
919 if($date == '0000-00-00' && $expiration_date) {
920 return __('Doesn\'t Expire', 'fslm');
921 }
922
923 if($date == '0000-00-00') {
924 return __('None', 'fslm');
925 }
926
927 if($date != '') {
928 $date = strtotime($date);
929 return date( 'M d, Y', $date);
930 }
931
932 return __('None', 'fslm');
933 }
934
935 function json_data_formatting_email($json, $order_id = -1){
936
937 $values = json_decode($json, true);
938 $val = "";
939 $visible_key_found = false;
940 $view_in_website = false;
941
942 if($values){
943 $val = "<h2>" . get_option('fslm_meta_key_name', 'License Key'). "</h2>
944 <table class=\"td\" cellspacing=\"0\" cellpadding=\"6\" style=\"width: 100%; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;\" border=\"1\">
945 <thead>
946 <tr>
947 <th class=\"td\" scope=\"col\" style=\"text-align:left;width: 20%;\"><strong>" . __('Product', 'fslm'). "</strong></th>
948 <th class=\"td\" scope=\"col\" style=\"text-align:left;width: 80%;\"><strong>" . get_option('fslm_meta_key_name', 'License Key'). "</strong></th>
949 </tr>
950 </thead>
951 <tbody>";
952
953 foreach($values as $value) {
954 if ($value['visible'] == 'Yes') {
955
956 $show_in = get_post_meta((int)$value['product_id'], 'fslm_show_in', true);
957
958 if ($show_in == "1") {
959 $view_in_website = true;
960 $visible_key_found = true;
961 break;
962 }
963
964 if ($show_in == "0" || $show_in == "2") {
965 $visible_key_found = true;
966
967 $display = get_post_meta((int)$value['product_id'], 'fslm_display', true);
968
969 $license_key = $value['license_key'];
970 $license_key = $this->encrypt_decrypt('decrypt', $license_key, ENCRYPTION_KEY, ENCRYPTION_VI);
971
972 $license_key = br2newLine($license_key);
973 $license_key = preg_replace( "/\\\\\"|\\\\'/", '"', $license_key);
974
975
976 if ($display != '1') {
977 $meta = $license_key . '<br>';;
978 }
979
980 $image_license_key = '';
981
982 if ($display != '0') {
983 $image_license_key = $this->get_image_name($value['license_id']);
984
985 if ($image_license_key != '') {
986 $upload_directory = wp_upload_dir();
987 $image_license_key = '<img style="width: auto" class="fslm_ilksrc" src="' . $upload_directory['baseurl'] . '/fslm_keys/' . $image_license_key . '">';
988 }
989 }
990
991 if ($value['max_instance_number'] > 0) {
992 $meta .= ' <strong>' . __('Can be used', 'fslm') . '</strong> ' . $value['max_instance_number'] . ' ' . __('time(s)', 'fslm') . '<br>';
993 }
994
995 if (($value['expiration_date'] != '0000-00-00') && ($value['expiration_date'] != '')) {
996 $meta .= ' ' . __('<strong>Expires</strong> ', 'fslm') . $this->format_date($value['expiration_date']);
997 }
998
999 $val .= '<tr><td class="td" scope="col" style="text-align:left;width: 20%;">' . get_the_title($value['product_id']) . '</td><td class="td" scope="col" style="text-align:left;width: 80%;">' . $meta . $image_license_key . '</td></tr>';
1000 }
1001 }
1002 }
1003
1004 $val .= "</tbody></table>";
1005 }
1006
1007 if($view_in_website) {
1008 $val = "<h2>" . get_option('fslm_meta_key_name', 'License Key'). "</h2> <p>" . __('Click here to see your') . ' <a href="' . get_permalink(get_option('fslm_page_id')) . '?lk=' . $order_id . '">' . get_option('fslm_meta_key_name_plural', 'License Keys') . "</a></p>";
1009 }
1010
1011 if($visible_key_found == false) $val = '';
1012
1013 return $val;
1014 }
1015
1016 function json_data_formatting_order_history($json){
1017
1018 $values = json_decode($json, true);
1019 $val = "";
1020 $visible_key_found = false;
1021
1022 if($values){
1023 $val = "<h2>" . get_option('fslm_meta_key_name', 'License Key'). "</h2>
1024 <table class=\"shop_table order_details\" style=\"width: 100%;\">
1025 <thead>
1026 <tr>
1027 <th style=\"text-align:left;width: 20%;\"><strong>" . __('Product', 'fslm'). "</strong></th>
1028 <th style=\"text-align:left;width: 80%;\"><strong>" . get_option('fslm_meta_key_name', 'License Key'). "</strong></th>
1029 </tr>
1030 </thead>
1031 <tbody>";
1032
1033 foreach($values as $value) {
1034 if ($value['visible'] == 'Yes') {
1035 $visible_key_found = true;
1036
1037 $display = get_post_meta((int)$value['product_id'], 'fslm_display', true);
1038
1039 $license_key = $value['license_key'];
1040 $license_key = $this->encrypt_decrypt('decrypt', $license_key, ENCRYPTION_KEY, ENCRYPTION_VI);
1041
1042 $license_key = br2newLine($license_key);
1043 $license_key = preg_replace( "/\\\\\"|\\\\'/", '"', $license_key);
1044
1045
1046 if ($display != '1') {
1047 $meta = $license_key . '<br>';
1048 }
1049
1050 $image_license_key = '';
1051
1052 if ($display != '0') {
1053 $image_license_key = $this->get_image_name($value['license_id']);
1054
1055 if ($image_license_key != '') {
1056 $upload_directory = wp_upload_dir();
1057 $image_license_key = '<img style="width: auto" class="fslm_ilksrc" src="' . $upload_directory['baseurl'] . '/fslm_keys/' . $image_license_key . '">';
1058 }
1059 }
1060
1061 if ($value['max_instance_number'] > 0) {
1062 $meta .= ' <strong>' . __('Can be used', 'fslm') . '</strong> ' . $value['max_instance_number'] . ' ' . __('time(s)', 'fslm') . '<br>';
1063 }
1064
1065 if (($value['expiration_date'] != '0000-00-00') && ($value['expiration_date'] != '')) {
1066 $meta .= ' ' . __('<strong>Expires</strong> ', 'fslm') . $this->format_date($value['expiration_date']);
1067 }
1068
1069 $val .= '<tr><td style="text-align:left;width: 20%;">' . get_the_title($value['product_id']) . '</td><td style="text-align:left;width: 80%;">' . $meta . $image_license_key . '</td></tr>';
1070 }
1071 }
1072
1073 $val .= "</tbody></table>";
1074 }
1075
1076 if($visible_key_found == false) $val = '';
1077
1078 return $val;
1079 }
1080
1081 function fslm_generator_rules_callback(){
1082 $product_id = $_POST['mbs_product_id'];
1083
1084 require_once('includes/metabox_rules_list.php');
1085
1086 echo fslm_metabox_rules_list($product_id);
1087
1088 die();
1089 }
1090
1091 /*****************/
1092 // Add license key to the email
1093 /*****************/
1094 function add_license_key_to_the_email($order){
1095
1096 $meta = get_post_meta($order->id, 'fslm_json_license_details', true);
1097
1098 $meta = str_replace("\\", "", $meta);
1099
1100 if(get_option('fslm_add_lk_wc_de', 'on') == 'on') {
1101 echo $this->json_data_formatting_email($meta, $order->id);
1102 }
1103
1104 }
1105
1106 /*****************/
1107 // See the license keys on the website
1108 /*****************/
1109 public function license_viewer(){
1110 if(isset($_GET['license'])){
1111 die();
1112 }
1113 }
1114
1115 /*****************/
1116 // Tracking API
1117 /*****************/
1118 public function api_requests_handler(){
1119 if(isset($_POST['fslmapirequest'])){
1120
1121
1122 if(($_POST['fslmapirequest'] == 'activate')&&(isset($_POST['license_key']))){
1123 $result = $this->activate_license_key(esc_sql($_POST['license_key']));
1124
1125 echo $result;
1126 }else if(($_POST['fslmapirequest'] == 'deactivate')&&(isset($_POST['license_key']))){
1127 $result = $this->deactivate_license_key(esc_sql($_POST['license_key']));
1128
1129 echo $result;
1130 }else if(($_POST['fslmapirequest'] == 'licenseVerification')&&(isset($_POST['license_key']))){
1131 $result = $this->license_verification(esc_sql($_POST['license_key']));
1132
1133 echo $result;
1134 }else if(($_POST['fslmapirequest'] == 'details')&&(isset($_POST['license_key']))){
1135 $result = $this->license_details(esc_sql($_POST['license_key']));
1136
1137 echo $result;
1138 }else if(($_POST['fslmapirequest'] == 'extra_data')&&(isset($_POST['product_id']))){
1139 $result = $this->get_product_extra_data($_POST['product_id']);
1140
1141 echo $result;
1142 }
1143
1144 die();
1145
1146 }
1147 }
1148
1149 public function get_product_extra_data($product_id) {
1150
1151 $json = '{';
1152
1153 $json .= '"software_name":"' . get_post_meta((int)$product_id, 'fslm_sn', true) . '",';
1154 $json .= '"software_id":"' . get_post_meta((int)$product_id, 'fslm_sid', true) . '",';
1155 $json .= '"software_version":"' . get_post_meta((int)$product_id, 'fslm_sv', true) . '",';
1156 $json .= '"software_author":"' . get_post_meta((int)$product_id, 'fslm_sa', true) . '",';
1157 $json .= '"software_url":"' . get_post_meta((int)$product_id, 'fslm_surl', true) . '",';
1158 $json .= '"software_last_update":"' . get_post_meta((int)$product_id, 'fslm_slu', true) . '",';
1159
1160 $software_extra_data = json_decode(get_post_meta((int)$product_id, 'fslm_sed', true));
1161 if (json_last_error() === JSON_ERROR_NONE) {
1162 $json .= '"software_extra_data":' . get_post_meta((int)$product_id, 'fslm_sed', true);
1163 } else {
1164 $json .= '"software_extra_data":"' . get_post_meta((int)$product_id, 'fslm_sed', true) . '"';
1165 }
1166
1167 $json .= "}";
1168
1169 return $json;
1170 }
1171
1172 /*****************/
1173 // Tracking API: Get license key details
1174 /*****************/
1175 public function license_details($license_key_decrypted){
1176 global $wpdb;
1177
1178 $license_key = $license_key_decrypted;
1179 $license_key = $this->encrypt_decrypt('encrypt', $license_key, ENCRYPTION_KEY, ENCRYPTION_VI);
1180
1181 $query = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}wc_fs_product_licenses_keys WHERE license_key='{$license_key}'");
1182
1183 if($query){
1184 $query = $query[0];
1185
1186 $query->license_key = $license_key_decrypted;
1187 return json_encode($query);
1188
1189 unset($query);
1190 }
1191
1192 return 'ERROR:INVALID_LICENSE_KEY';
1193 }
1194
1195 /*****************/
1196 // Tracking API: activate license key
1197 /*****************/
1198 public function activate_license_key($license_key_decrypted){
1199 global $wpdb;
1200
1201 $license_key = $license_key_decrypted;
1202 $license_key = $this->encrypt_decrypt('encrypt', $license_key, ENCRYPTION_KEY, ENCRYPTION_VI);
1203
1204 $verification = $this->license_verification($license_key_decrypted);
1205
1206 if($verification == 'VALID'){
1207 $query = $wpdb->get_results("SELECT number_use_remaining FROM {$wpdb->prefix}wc_fs_product_licenses_keys WHERE license_key='{$license_key}'");
1208
1209 if($query){
1210 $query = $query[0];
1211
1212 $number_use_remaining = $query->number_use_remaining;
1213
1214 if($number_use_remaining > 0){
1215
1216 $data = array(
1217 'number_use_remaining' => $number_use_remaining-1,
1218 'activation_date' => date('Y-m-d H:i:s'),
1219 'license_status' => 'active'
1220 );
1221
1222 $where = array(
1223 'license_key' => $license_key
1224 );
1225 $result = $wpdb->update("{$wpdb->prefix}wc_fs_product_licenses_keys", $data, $where);
1226
1227 return($result==1)?'OK':'ERROR';
1228 }else {
1229 return 'ERROR:MAX';
1230 }
1231
1232 }
1233
1234 return 'ERROR:INVALID_LICENSE_KEY';
1235 }else {
1236 return $verification;
1237 }
1238
1239 }
1240
1241 /*****************/
1242 // Tracking API: License Verification
1243 /*****************/
1244 public function license_verification($license_key_decrypted){
1245 global $wpdb;
1246
1247 $license_key = $license_key_decrypted;
1248 $license_key = $this->encrypt_decrypt('encrypt', $license_key, ENCRYPTION_KEY, ENCRYPTION_VI);
1249
1250 $query = $wpdb->get_results("SELECT expiration_date FROM {$wpdb->prefix}wc_fs_product_licenses_keys WHERE license_key='{$license_key}'");
1251
1252 if($query){
1253 $query = $query[0];
1254
1255 $expiration_date = $query->expiration_date;
1256
1257 unset($query);
1258 if(strtotime($expiration_date)> time()|| $expiration_date == '0000-00-00'){
1259 return 'VALID';
1260 }
1261
1262 return 'ERROR:EXPIRED';
1263
1264 }
1265
1266 return 'ERROR:INVALID_LICENSE_KEY';
1267
1268 }
1269
1270 /*****************/
1271 // Tracking API: deactivate license key
1272 /*****************/
1273 public function deactivate_license_key($license_key_decrypted){
1274 global $wpdb;
1275
1276 $license_key = $license_key_decrypted;
1277 $license_key = $this->encrypt_decrypt('encrypt', $license_key, ENCRYPTION_KEY, ENCRYPTION_VI);
1278
1279 $verification = $this->license_verification($license_key_decrypted);
1280
1281 if($verification == 'VALID'){
1282 $query = $wpdb->get_results("SELECT max_instance_number, number_use_remaining, license_status FROM {$wpdb->prefix}wc_fs_product_licenses_keys WHERE license_key='{$license_key}'");
1283 if($query){
1284 $query = $query[0];
1285
1286 $max_instance_number = $query->max_instance_number;
1287 $number_use_remaining = $query->number_use_remaining;
1288 $license_status = $query->license_status;
1289
1290 $active =($number_use_remaining+1 == $max_instance_number)?'inactive':$license_status;
1291
1292 if($number_use_remaining < $max_instance_number){
1293
1294 $data = array(
1295 'number_use_remaining' => $number_use_remaining+1,
1296 'license_status' => $active
1297 );
1298
1299 $where = array(
1300 'license_key' => $license_key
1301 );
1302 $result = $wpdb->update("{$wpdb->prefix}wc_fs_product_licenses_keys", $data, $where);
1303
1304 return($result==1)?'OK':'ERROR';
1305 }else {
1306 return 'ERROR:INACTIVE';
1307 }
1308
1309 }
1310
1311 return 'ERROR:INVALID_LICENSE_KEY';
1312 }else {
1313 return $verification;
1314 }
1315
1316 }
1317
1318
1319 /*****************/
1320 // Cart check
1321 /*****************/
1322 function validate_cart_content(){
1323 global $wpdb;
1324
1325 foreach(WC()->cart->cart_contents as $cart_product){
1326
1327 $product = $cart_product['data'];
1328
1329 if(($this->is_licensing_enabled($cart_product['product_id'], $cart_product['variation_id'])) && (!$this->isGeneratorActive($cart_product['product_id'], $cart_product['variation_id']))){
1330
1331 $nb_delivered_keys = get_post_meta((int)$cart_product['product_id'], 'fslm_nb_delivered_lk', true);
1332 $lk_count = 0;
1333 $query = $wpdb->get_results("SELECT remaining_delivre_x_times FROM {$wpdb->prefix}wc_fs_product_licenses_keys WHERE product_id='{$cart_product['product_id']}' AND variation_id = '{$cart_product['variation_id']}' AND license_status='available'");
1334 $porduct_name = $product->get_title();
1335
1336 if($query){
1337 foreach($query as $query){
1338 $lk_count = $lk_count +(int)($query->remaining_delivre_x_times);
1339 }
1340 }
1341
1342 $nb_licenses = get_post_meta((int)$cart_product['product_id'], 'fslm_nb_delivered_lk', true);
1343 if(empty($nb_licenses)|| $nb_licenses == 0)$nb_licenses = 1;
1344
1345 $qty =(int)$cart_product['quantity'] *(int)$nb_licenses;
1346
1347 $item = '<strong>' . $porduct_name . '</strong>';
1348
1349 if($cart_product['variation_id']!='0'){
1350 $single_variation = new WC_Product_Variation($cart_product['variation_id']);
1351 $item .= ' ' . __('product variation', 'fslm'). ' ' . $single_variation->get_formatted_name();
1352 }
1353
1354 $pqty = '';
1355 if((int)$nb_delivered_keys > 1){
1356 $pqty = '<br>' . $nb_delivered_keys . ' ' . __('License Key(s) are delivered per purchase. Only', 'fslm'). ' ' . floor($lk_count/$nb_delivered_keys). ' ' . __('purchase(s) possible.', 'fslm');
1357 }
1358
1359
1360 if($lk_count < $qty){
1361 wc_add_notice(__('Sorry, There is no license keys available for', 'fslm').' '. $item . ', <br>'. __('Please remove this item or lower the quantity, For now we have', 'fslm'). ' ' . $lk_count . ' ' . __('License key(s)', 'fslm'). ' ' . __('for this product.', 'fslm'). $pqty . '<br>', 'error');
1362 }
1363 }
1364 }
1365
1366 }
1367
1368 /*****************/
1369 // check if automatic license key generator if active
1370 /*****************/
1371 function isGeneratorActive($product_id, $variation_id = 0){
1372 global $wpdb;
1373 return $wpdb->get_var("SELECT active FROM {$wpdb->prefix}wc_fs_product_licenses_keys_generator_rules WHERE product_id = '{$product_id}' AND variation_id = '{$variation_id}' AND active = '1'")=='1'?true:false;
1374 }
1375
1376
1377 public function fslm_revoke_license_keys($order_id){
1378 global $wpdb;
1379
1380 $post_meta = get_post_meta($order_id, 'fslm_json_license_details', true);
1381
1382 $meta = str_replace("\\", "", $meta);
1383
1384 $values = json_decode($post_meta, true);
1385 $license_ids = array();
1386
1387 if($values) {
1388 foreach ($values as $value) {
1389 $license_ids[] = $value['license_id'];
1390 }
1391
1392 $sql = "UPDATE {$wpdb->prefix}wc_fs_product_licenses_keys SET license_status = 'returned' WHERE license_id IN([IN])";
1393 $sql = $this->prepare_in($sql, $license_ids);
1394
1395 $wpdb->query($sql);
1396 }
1397
1398 delete_post_meta($order_id, 'fslm_licensed');
1399 delete_post_meta($order_id, 'fslm_json_license_details');
1400 }
1401
1402 public function fslm_hide_license_keys($order_id){
1403 $post_meta = get_post_meta($order_id, 'fslm_json_license_details', true);
1404
1405 $post_meta = str_replace("\\", "", $post_meta);
1406
1407 $values = json_decode($post_meta, true);
1408 $json = '';
1409
1410 if($values) {
1411 foreach ($values as $key => $value) {
1412 $values[$key]['visible'] = 'No';
1413 }
1414
1415 $values = array_values($values);
1416 $json = json_encode($values, JSON_FORCE_OBJECT);
1417
1418
1419 update_post_meta($order_id, 'fslm_json_license_details', $json);
1420 }
1421
1422
1423
1424 }
1425
1426 /*****************/
1427 // Send license key(s)
1428 /*****************/
1429 public function fslm_send_license_keys($order_id){
1430 global $woocommerce, $table_prefix, $wpdb;
1431
1432 $order = new WC_Order($order_id);
1433
1434
1435
1436 $on_status = array('completed');
1437 $order_status_key = str_replace("wc-", "", strtolower($order->post_status));
1438 $default = 'off';
1439 if(in_array($order_status_key, $on_status))$default = 'on';
1440
1441 if(get_option('fslm_send_when_' . $order_status_key, $default) != 'on'){
1442 return false;
1443 }
1444
1445 if(add_post_meta($order_id, 'fslm_licensed', 'true', true)){
1446
1447 $json_license_details = '{';
1448 $index = 0;
1449
1450 $ids = array();
1451 $items = $order->get_items();
1452
1453 foreach($items as $item => $value){
1454 $nb_licenses = get_post_meta((int)$value['product_id'], 'fslm_nb_delivered_lk', true);
1455 if(empty($nb_licenses))$nb_licenses = 1;
1456
1457 $qty =(int)$value['qty'] *(int)$nb_licenses;
1458 $nd_delivered = 0;
1459 $remaining_delivre_x_times = 0;
1460
1461 if($this->is_licensing_enabled($value['product_id'], $value['variation_id'])){
1462
1463 $query = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}wc_fs_product_licenses_keys WHERE product_id = '{$value['product_id']}' AND variation_id = '{$value['variation_id']}' AND license_status = 'available' AND remaining_delivre_x_times > 0 ORDER BY license_id DESC LIMIT 0, {$qty}");
1464
1465 if($query){
1466 foreach($query as $query){
1467 if($qty <= 0)break;
1468
1469 $ids[] = $query->license_id;
1470
1471 $license_key = $query->license_key;
1472
1473 $max_instance_number = $query->max_instance_number;
1474 $expiration_date = $query->expiration_date;
1475 $valid = $query->valid;
1476 $remaining_delivre_x_times = $query->remaining_delivre_x_times;
1477
1478
1479
1480 $served = false;
1481
1482 if($qty > 0){
1483
1484 if(($remaining_delivre_x_times > 1)&&($remaining_delivre_x_times <= $qty)){
1485 $served = true;
1486 $nd_delivered = $remaining_delivre_x_times;
1487 $qty = $qty -($query->remaining_delivre_x_times);
1488
1489 $json_license_details .= '"' . $index . '":{"license_id":"' . $query->license_id . '",';
1490 $json_license_details .= '"item_id":"' . $item . '",';
1491 $json_license_details .= '"product_id":"' . $value['product_id'] . '",';
1492 $json_license_details .= '"variation_id":"' . $value['variation_id'] . '",';
1493 $json_license_details .= '"license_key":"' . $license_key . '",';
1494 $json_license_details .= '"max_instance_number":"' . $max_instance_number . '",';
1495 $json_license_details .= '"visible":"Yes",';
1496 if ($valid > 0) {
1497 $json_license_details .= '"expiration_date":"' . date('Y-m-d', strtotime(date('Y-m-d') . ' + ' . $valid . ' ' . 'days')) . '"},';
1498 } else if (($expiration_date != '0000-00-00') && ($expiration_date != '')) {
1499 $json_license_details .= '"expiration_date":"' . $expiration_date . '"},';
1500 } else {
1501 $json_license_details .= '"expiration_date":"0000-00-00"},';
1502 }
1503
1504 }
1505
1506 if(($remaining_delivre_x_times > 1)&&($remaining_delivre_x_times > $qty)&&($served == false)){
1507 $served = true;
1508 $nd_delivered = $qty;
1509 $qty = 0;
1510
1511 $json_license_details .= '"' . $index . '":{"license_id":"' . $query->license_id . '",';
1512 $json_license_details .= '"item_id":"' . $item . '",';
1513 $json_license_details .= '"product_id":"' . $value['product_id'] . '",';
1514 $json_license_details .= '"variation_id":"' . $value['variation_id'] . '",';
1515 $json_license_details .= '"license_key":"' . $license_key . '",';
1516 $json_license_details .= '"max_instance_number":"' . $max_instance_number . '",';
1517 $json_license_details .= '"visible":"Yes",';
1518 if ($valid > 0) {
1519 $json_license_details .= '"expiration_date":"' . date('Y-m-d', strtotime(date('Y-m-d') . ' + ' . $valid . ' ' . 'days')) . '"},';
1520 } else if (($expiration_date != '0000-00-00') && ($expiration_date != '')) {
1521 $json_license_details .= '"expiration_date":"' . $expiration_date . '"},';
1522 } else {
1523 $json_license_details .= '"expiration_date":"0000-00-00"},';
1524 }
1525 }
1526
1527 if(($remaining_delivre_x_times == 1)&&($served == false)){
1528 $served = true;
1529 $qty--;
1530
1531 $json_license_details .= '"' . $index . '":{"license_id":"' . $query->license_id . '",';
1532 $json_license_details .= '"item_id":"' . $item . '",';
1533 $json_license_details .= '"product_id":"' . $value['product_id'] . '",';
1534 $json_license_details .= '"variation_id":"' . $value['variation_id'] . '",';
1535 $json_license_details .= '"license_key":"' . $license_key . '",';
1536 $json_license_details .= '"max_instance_number":"' . $max_instance_number . '",';
1537 $json_license_details .= '"visible":"Yes",';
1538 if ($valid > 0) {
1539 $json_license_details .= '"expiration_date":"' . date('Y-m-d', strtotime(date('Y-m-d') . ' + ' . $valid . ' ' . 'days')) . '"},';
1540 } else if (($expiration_date != '0000-00-00') && ($expiration_date != '')) {
1541 $json_license_details .= '"expiration_date":"' . $expiration_date . '"},';
1542 } else {
1543 $json_license_details .= '"expiration_date":"0000-00-00"},';
1544 }
1545 }
1546
1547 if($remaining_delivre_x_times == 1){
1548
1549 $sql = "UPDATE {$wpdb->prefix}wc_fs_product_licenses_keys SET license_status = 'sold', remaining_delivre_x_times = remaining_delivre_x_times - 1, owner_first_name = '{$order->billing_first_name}', owner_last_name = '$order->billing_last_name', owner_email_address = '$order->billing_email' WHERE license_id = '$query->license_id'";
1550
1551 }else if($remaining_delivre_x_times <= $nd_delivered){
1552
1553 $sql = "UPDATE {$wpdb->prefix}wc_fs_product_licenses_keys SET license_status = 'sold', remaining_delivre_x_times = remaining_delivre_x_times - {$nd_delivered}, owner_first_name = '{$order->billing_first_name}', owner_last_name = '$order->billing_last_name', owner_email_address = '$order->billing_email' WHERE license_id = '$query->license_id'";
1554
1555 }else if($remaining_delivre_x_times > $nd_delivered){
1556
1557 $sql = "UPDATE {$wpdb->prefix}wc_fs_product_licenses_keys SET remaining_delivre_x_times = remaining_delivre_x_times - {$nd_delivered}, owner_first_name = '{$order->billing_first_name}', owner_last_name = '$order->billing_last_name', owner_email_address = '$order->billing_email' WHERE license_id = '$query->license_id'";
1558 }
1559 $wpdb->query($sql);
1560
1561 $index++;
1562
1563 }
1564 }
1565
1566 }
1567
1568
1569 if($this->isGeneratorActive($value['product_id'], $value['variation_id'])){
1570
1571 $query = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}wc_fs_product_licenses_keys_generator_rules WHERE product_id = '{$value['product_id']}' AND variation_id = '{$value['variation_id']}' AND active = '1'");
1572
1573 if($query){
1574 $query = $query[0];
1575
1576 for($i=0; $i<$qty; $i++){
1577 $prefix = $query->prefix;
1578 $chunks_number = $query->chunks_number;
1579 $chunks_length = $query->chunks_length;
1580 $suffix = $query->suffix;
1581 $max_instance_number = $query->max_instance_number;
1582 $valid = $query->valid;
1583 $expires = "0000-00-00";
1584
1585
1586
1587 $license_key = $this->generate_license_key($prefix, $chunks_number, $chunks_length, $suffix);
1588 $license_key = $this->encrypt_decrypt('encrypt', $license_key, ENCRYPTION_KEY, ENCRYPTION_VI);
1589 while($this->licenseKeyExist($license_key)){
1590 $license_key = $this->generate_license_key($prefix, $chunks_number, $chunks_length, $suffix);
1591 $license_key = $this->encrypt_decrypt('encrypt', $license_key, ENCRYPTION_KEY, ENCRYPTION_VI);
1592 }
1593
1594 $json_license_details .= '"' . $index . '":{"license_id":"' . $query->license_id . '",';
1595 $json_license_details .= '"item_id":"' . $item . '",';
1596 $json_license_details .= '"product_id":"' . $value['product_id'] . '",';
1597 $json_license_details .= '"variation_id":"' . $value['variation_id'] . '",';
1598 $json_license_details .= '"license_key":"' . $license_key . '",';
1599 $json_license_details .= '"max_instance_number":"' . $max_instance_number . '",';
1600 $json_license_details .= '"visible":"Yes",';
1601 if ($valid > 0) {
1602 $expires = date('Y-m-d', strtotime(date('Y-m-d') . ' + ' . $valid . ' ' . 'days'));
1603 $json_license_details .= '"expiration_date":"' . $expires . '"},';
1604 } else {
1605 $json_license_details .= '"expiration_date":"0000-00-00"},';
1606 }
1607
1608 $data = array(
1609 'product_id' => $value['product_id'],
1610 'license_key' => $license_key,
1611 'variation_id' => $value['variation_id'],
1612 'max_instance_number' => $max_instance_number,
1613 'owner_first_name' => $order->billing_first_name,
1614 'owner_last_name' => $order->billing_last_name,
1615 'owner_email_address' => $order->billing_email,
1616 'number_use_remaining' => $max_instance_number,
1617 'creation_date' => date('Y-m-d H:i:s'),
1618 'expiration_date' => $expires . ' 0:0:0',
1619 'delivre_x_times' => '0',
1620 'remaining_delivre_x_times' => '0',
1621 'valid' => $valid,
1622 'license_status' => 'sold'
1623 );
1624 $wpdb->insert("{$wpdb->prefix}wc_fs_product_licenses_keys", $data);
1625
1626 $index++;
1627 }
1628 }
1629 }
1630 }
1631 }
1632
1633 $json_license_details = rtrim($json_license_details, ",");
1634 $json_license_details .= '}';
1635 add_post_meta($order_id, 'fslm_json_license_details', $json_license_details, true);
1636
1637 }
1638
1639 }
1640
1641 public function lr_callback() {
1642
1643 $eu = $_POST['pcu'];
1644 $pc = $_POST['pc'];
1645
1646 if($this->is_pc_valid($pc)) {
1647
1648 $this->license($pc, $eu);
1649
1650 $link = admin_url('admin.php?page=license-manager');
1651 wp_redirect($link);
1652
1653 die();
1654 }
1655
1656
1657 $link = admin_url('admin.php?page=license-manager-welcome&_ipc');
1658 wp_redirect($link);
1659 die();
1660
1661 }
1662
1663 public function rv_callback() {
1664
1665 $eu = $_POST['pcu'];
1666 $pc = $_POST['pc'];
1667 $notice = $_POST['notice'];
1668
1669 if($this->is_pc_valid($pc)) {
1670
1671 $this->rv_license($pc, $eu);
1672
1673 if($notice != "" && $notice != '1') {
1674 update_option('fslm_license_status_admin_notice', true);
1675 update_option('fslm_license_status_admin_notice_txt', $notice);
1676
1677 }elseif($notice == "") {
1678 update_option('fslm_license_status_admin_notice', false);
1679 update_option('fslm_license_status_admin_notice_txt', '');
1680 }
1681
1682 }
1683
1684 die();
1685
1686 }
1687
1688 /*****************/
1689 // Check if a license key is unique
1690 /*****************/
1691 public function licenseKeyExist($license_key){
1692 global $wpdb;
1693
1694 return((int)$wpdb->get_var("SELECT COUNT(*)FROM {$wpdb->prefix}wc_fs_product_licenses_keys WHERE license_key='{$license_key}'")>0)?true:false;
1695 }
1696
1697 /*****************/
1698 // Generate License Key
1699 /*****************/
1700 public function generate_license_key($prefix, $chunks_number, $chunks_length, $suffix){
1701 $charset = get_option('fslm_generator_chars', '0123456789ABCDEF');
1702 $base = strlen($charset);
1703 $result = '';
1704 $tmp_result = '';
1705
1706 for($j=0; $j<$chunks_number; $j++){
1707 $now = rand(1000,100000);
1708
1709 while(($now >= $base)||(strlen($tmp_result)<$chunks_length)){
1710 $i = $now % $base;
1711 $tmp_result = $charset[$i] . $tmp_result;
1712 $now /= $base;
1713 }
1714
1715 $result .= substr($tmp_result, 0, $chunks_length);
1716 if($j<$chunks_number-1)$result .= '-';
1717 }
1718
1719 return $prefix . $result . $suffix;
1720 }
1721
1722 /*****************/
1723 // Save Metabox on post save
1724 /*****************/
1725 public function save_product($post_id){
1726 global $wpdb;
1727
1728 if((isset($_POST['post_type'])&& $_POST['post_type'] != 'product')||(!isset($_POST['post_type'])))
1729 return false;
1730
1731 $product_id =(isset($_POST['mbs_product_id']))?$_POST['mbs_product_id']:'';
1732 $variation_id =(isset($_POST['mbs_variation_id']))?$_POST['mbs_variation_id']:'0';
1733
1734 $software_name = $_POST['fslm_sn'];
1735 $software_ID = $_POST['fslm_sid'];
1736 $software_version = $_POST['fslm_sv'];
1737 $software_author = $_POST['fslm_sa'];
1738 $software_url = $_POST['fslm_surl'];
1739 $software_last_update = $_POST['fslm_slu'];
1740 $software_extra_data = $_POST['fslm_sed'];
1741
1742 if(!add_post_meta((int)$product_id, 'fslm_sn', $software_name, true)){
1743 update_post_meta((int)$product_id, 'fslm_sn', $software_name);
1744 }
1745
1746 if(!add_post_meta((int)$product_id, 'fslm_sid', $software_ID, true)){
1747 update_post_meta((int)$product_id, 'fslm_sid', $software_ID);
1748 }
1749
1750 if(!add_post_meta((int)$product_id, 'fslm_sv', $software_version, true)){
1751 update_post_meta((int)$product_id, 'fslm_sv', $software_version);
1752 }
1753
1754 if(!add_post_meta((int)$product_id, 'fslm_sa', $software_author, true)){
1755 update_post_meta((int)$product_id, 'fslm_sa', $software_author);
1756 }
1757
1758 if(!add_post_meta((int)$product_id, 'fslm_surl', $software_url, true)){
1759 update_post_meta((int)$product_id, 'fslm_surl', $software_url);
1760 }
1761
1762 if(!add_post_meta((int)$product_id, 'fslm_slu', $software_last_update, true)){
1763 update_post_meta((int)$product_id, 'fslm_slu', $software_last_update);
1764 }
1765
1766 if(!add_post_meta((int)$product_id, 'fslm_sed', $software_extra_data, true)){
1767 update_post_meta((int)$product_id, 'fslm_sed', $software_extra_data);
1768 }
1769
1770 $licensable = (isset($_POST['mbs_licensable'])&& $_POST['mbs_licensable'] == 'on')?'1':'0';
1771 $active = (isset($_POST['mbs_active'])&& $_POST['mbs_active'] == 'on')?'1':'0';
1772 $prefix = (isset($_POST['mbs_prefix']))?$_POST['mbs_prefix']:'';
1773 $chunks_number = (isset($_POST['mbs_chunks_number']))?$_POST['mbs_chunks_number']:'';
1774 $chunks_length = (isset($_POST['mbs_chunks_length']))?$_POST['mbs_chunks_length']:'';
1775 $suffix = (isset($_POST['mbs_suffix']))?$_POST['mbs_suffix']:'';
1776 $max_instance_number = (isset($_POST['mbs_max_instance_number']))?$_POST['mbs_max_instance_number']:'';
1777 $valid = (isset($_POST['mbs_valid']))?$_POST['mbs_valid']:'';
1778
1779 $this->set_licensing($product_id, '0', $licensable);
1780
1781
1782 $handle = new WC_Product_Variable($product_id);
1783
1784 $variations = $handle->get_children();
1785 foreach ($variations as $variation) {
1786 $single_variation = new WC_Product_Variation($variation);
1787 $licensable_variation =(isset($_POST["mbs_licensable_{$variation}"])&& $_POST["mbs_licensable_{$variation}"] == 'on')?'1':'0';
1788
1789 $this->set_licensing($product_id, $variation, $licensable_variation);
1790 }
1791
1792 $show_in = (isset($_POST['fslm_show_in']))?$_POST['fslm_show_in']:'';
1793 $display = (isset($_POST['fslm_display']))?$_POST['fslm_display']:'';
1794
1795 if(!add_post_meta((int)$product_id, 'fslm_show_in', $show_in, true)){
1796 update_post_meta((int)$product_id, 'fslm_show_in', $show_in);
1797 }
1798
1799 if(!add_post_meta((int)$product_id, 'fslm_display', $display, true)){
1800 update_post_meta((int)$product_id, 'fslm_display', $display);
1801 }
1802
1803 $nb_delivered_lk = $_POST['fslm_nb_delivered_lk'];
1804
1805 if(!add_post_meta((int)$product_id, 'fslm_nb_delivered_lk', $nb_delivered_lk, true)){
1806 update_post_meta((int)$product_id, 'fslm_nb_delivered_lk', $nb_delivered_lk);
1807 }
1808
1809 $data = array(
1810 'product_id' => $product_id,
1811 'variation_id' => $variation_id,
1812 'prefix' => $prefix,
1813 'chunks_number' => $chunks_number,
1814 'chunks_length' => $chunks_length,
1815 'suffix' => $suffix,
1816 'max_instance_number' => $max_instance_number,
1817 'valid' => $valid,
1818 'active' => $active
1819 );
1820
1821 $exist =(int)$wpdb->get_var("SELECT COUNT(*)FROM {$wpdb->prefix}wc_fs_product_licenses_keys_generator_rules WHERE product_id = '" . $product_id . "'");
1822
1823 if($exist == 0){
1824 $wpdb->insert("{$wpdb->prefix}wc_fs_product_licenses_keys_generator_rules", $data);
1825 }else {
1826 $where = array(
1827 'product_id' => $product_id
1828 );
1829
1830 $wpdb->update("{$wpdb->prefix}wc_fs_product_licenses_keys_generator_rules", $data, $where);
1831 }
1832 }
1833
1834 /*****************/
1835 // Import License Keys Only callback
1836 /*****************/
1837 public function import_lko_callback(){
1838 global $wpdb;
1839
1840 if(isset($_FILES['ilk_source_file'])&& $_FILES['ilk_source_file']['size'] > 0){
1841 $tmp = wp_tempnam($_FILES['ilk_source_file']['name']);
1842 move_uploaded_file($_FILES['ilk_source_file']['tmp_name'], $tmp);
1843
1844 $file = fopen($tmp, 'r');
1845 $content = fread($file, $_FILES['ilk_source_file']['size']);
1846 fclose($file);
1847
1848 $lines = explode("\n", $content);
1849
1850 $product_id = $_POST['product_id'];
1851 $variation_id = $_POST['variation_id'];
1852 $max_instance_number =(int)$_POST['max_instance_number'];
1853 $yy =(int)$_POST['yy'];
1854 $mm =(int)$_POST['mm'];
1855 $dd =(int)$_POST['dd'];
1856 $valid =(int)$_POST['valid'];
1857
1858
1859 $deliver_x_times = $_POST['deliver_x_times'];
1860
1861 foreach($lines as $line){
1862 if($line != ''){
1863 $license_key = str_replace(array("\r", "\n"), '', $line);
1864
1865 $license_key = $this->encrypt_decrypt('encrypt', $license_key, ENCRYPTION_KEY, ENCRYPTION_VI);
1866
1867 $data = array(
1868 'product_id' => $product_id,
1869 'variation_id' => $variation_id,
1870 'license_key' => $license_key,
1871 'image_license_key' => '',
1872 'delivre_x_times' => $deliver_x_times,
1873 'remaining_delivre_x_times' => $deliver_x_times,
1874 'max_instance_number' => $max_instance_number,
1875 'number_use_remaining' => $max_instance_number,
1876 'creation_date' => date('Y-m-d H:i:s'),
1877 'expiration_date' => $yy . '-' . $mm . '-' . $dd . ' 0:0:0',
1878 'valid' => $valid,
1879 'license_status' => 'available'
1880 );
1881 $variation = wc_get_product( $variation_id );
1882 $variation->set_stock_quantity($variation->get_stock_quantity() + 1);
1883 $variation->save();
1884 $wpdb->insert("{$wpdb->prefix}wc_fs_product_licenses_keys", $data);
1885 }
1886 }
1887 }
1888
1889 $link = admin_url('admin.php?page=license-manager#hlk');
1890 wp_redirect($link);
1891 die();
1892 }
1893
1894 /*****************/
1895 // Import License Keys callback
1896 /*****************/
1897 public function import_csv_lk_callback(){
1898 global $wpdb;
1899
1900 if(isset($_FILES['ilk_source_file'])&& $_FILES['ilk_source_file']['size'] > 0){
1901 $tmp = wp_tempnam($_FILES['ilk_source_file']['name']);
1902 move_uploaded_file($_FILES['ilk_source_file']['tmp_name'], $tmp);
1903
1904 $file = fopen($tmp, 'r');
1905 $content = fread($file, $_FILES['ilk_source_file']['size']);
1906 fclose($file);
1907
1908 $lines = explode("\n", $content);
1909
1910 $i = 0;
1911 $query = "INSERT INTO {$wpdb->prefix}wc_fs_product_licenses_keys(";
1912 $columns_array = "";
1913 $values_array = "";
1914 $values = "";
1915
1916 foreach($lines as $line){
1917 if($i == 0 || $line == ''){
1918 $i++;
1919 continue;
1920 }else if($i == 1){
1921
1922 $columns_array = explode('","', substr(trim($line), 1, strlen($line)-2));
1923 //$columns_array = array_splice($columns_array, 1);
1924
1925 $query .= implode(', ', $columns_array). ')VALUES(';
1926
1927 $i++;
1928 continue;
1929 }else {
1930
1931 $values_array = explode('","', substr(trim($line), 1, strlen($line)-2));
1932 //$values_array = array_splice($values_array, 1);
1933
1934 //$values_array[2] = $this->encrypt_decrypt('encrypt', $values_array[2], ENCRYPTION_KEY, ENCRYPTION_VI);
1935
1936 $values = '"' . implode('","', $values_array). '")ON DUPLICATE KEY UPDATE ';
1937
1938 $c = 0;
1939 foreach($columns_array as $column){
1940 //if($column != 'license_key'){
1941 $values .= $column . ' = "' . $values_array[$c] . '", ';
1942 // }
1943 $c++;
1944 }
1945
1946 $values = substr(trim($values), 0, strlen($values)-2);
1947
1948
1949 $wpdb->query($query . $values);
1950
1951 }
1952 }
1953 }
1954
1955
1956 $link = admin_url('admin.php?page=license-manager#hlk');
1957 wp_redirect($link);
1958 die();
1959 }
1960
1961
1962 /*****************/
1963 // Import Generator Rules callback
1964 /*****************/
1965 public function import_csv_gr_callback(){
1966 global $wpdb;
1967
1968 if(isset($_FILES['igr_source_file'])&& $_FILES['igr_source_file']['size'] > 0){
1969 $tmp = wp_tempnam($_FILES['igr_source_file']['name']);
1970 move_uploaded_file($_FILES['igr_source_file']['tmp_name'], $tmp);
1971
1972 $file = fopen($tmp, 'r');
1973 $content = fread($file, $_FILES['igr_source_file']['size']);
1974 fclose($file);
1975
1976 $lines = explode("\n", $content);
1977
1978 $i = 0;
1979 $query = "INSERT INTO {$wpdb->prefix}wc_fs_product_licenses_keys_generator_rules(";
1980 $columns_array = "";
1981 $values_array = "";
1982 $values = "";
1983
1984 foreach($lines as $line){
1985 if($i == 0 || $line == ''){
1986 $i++;
1987 continue;
1988 }else if($i == 1){
1989
1990 $columns_array = explode('","', substr(trim($line), 1, strlen($line)-2));
1991 $columns_array = array_splice($columns_array, 1);
1992 $query .= implode(', ', $columns_array). ')VALUES(';
1993
1994 $i++;
1995 continue;
1996 }else {
1997
1998 $values_array = explode('","', substr(trim($line), 1, strlen($line)-2));
1999 $values_array = array_splice($values_array, 1);
2000 $values = '"' . implode('","', $values_array). '")ON DUPLICATE KEY UPDATE ';
2001
2002 $c = 0;
2003 foreach($columns_array as $column){
2004 $values .= $column . ' = "' . $values_array[$c] . '", ';
2005 $c++;
2006 }
2007
2008 $values = substr(trim($values), 0, strlen($values)-2);
2009
2010 $wpdb->query($query . $values);
2011 }
2012 }
2013 }
2014
2015
2016 $link = admin_url('admin.php?page=license-manager-license-key-generator');
2017 wp_redirect($link);
2018 die();
2019 }
2020
2021 /*****************/
2022 // Import Plugin Settings callback
2023 /*****************/
2024 public function import_ps_callback(){
2025
2026 if(isset($_FILES['ips_source_file'])&& $_FILES['ips_source_file']['size'] > 0){
2027 $tmp = wp_tempnam($_FILES['ips_source_file']['name']);
2028 move_uploaded_file($_FILES['ips_source_file']['tmp_name'], $tmp);
2029
2030 $file = fopen($tmp, 'r');
2031 $content = fread($file, $_FILES['ips_source_file']['size']);
2032 fclose($file);
2033
2034 $lines = explode("\n", $content);
2035
2036 foreach($lines as $line){
2037 if($line != ''){
2038 $element = explode(" => ", $line);
2039 if($element[0] == "fslm_encryption") {
2040 $keys = explode("[SEP]", $element[1]);
2041
2042 $this->set_encryption_key($keys[0], $keys[1]);
2043 }else {
2044 update_option($element[0], str_replace("[NL]", "\n", $element[1]));
2045 }
2046 }
2047 }
2048 }
2049
2050 $link = admin_url('admin.php?page=license-manager-settings');
2051 wp_redirect($link);
2052 die();
2053 }
2054
2055 /*****************/
2056 // Export License Keys callback
2057 /*****************/
2058 public function export_csv_lk_callback(){
2059
2060 $license_status = '';
2061 $product_id = '';
2062
2063 if(isset($_REQUEST['elk_license_status'])&& $_REQUEST['elk_license_status'] != 'all'){
2064 $license_status = $_REQUEST['elk_license_status'];
2065 }
2066
2067 if(isset($_REQUEST['elk_product_id'])&& $_REQUEST['elk_product_id'] != 'all'){
2068 $product_id = $_REQUEST['elk_product_id'];
2069 }
2070
2071 header('Content-Type: application/csv');
2072 header('Content-Disposition: attachement; filename="license_manager__license_keys__' . date("__d_m_Y__H_i_s"). '__' . $_REQUEST['elk_product_id'] .'__' . $_REQUEST['elk_license_status'] . '.csv";');
2073 echo $this->generate_license_keys_csv($license_status, $product_id);
2074 die();
2075 }
2076
2077 /*****************/
2078 // Export Generator Rules callback
2079 /*****************/
2080 public function export_csv_gr_callback(){
2081 $product_id = '';
2082 if(isset($_REQUEST['egr_product_id'])&& $_REQUEST['egr_product_id'] != 'all'){
2083 $product_id = $_REQUEST['egr_product_id'];
2084 }
2085 header('Content-Type: application/csv');
2086 header('Content-Disposition: attachement; filename="license_manager__generator_rules_' . date("__d_m_Y__H_i_s"). '__' . $_REQUEST['egr_product_id'] . '.csv";');
2087 echo $this->generate_generator_rules_csv();
2088 die();
2089 }
2090
2091 /*****************/
2092 // Export Plugin Settings callback
2093 /*****************/
2094 public function export_ps_callback(){
2095 header('Content-Type: application/csv');
2096 header('Content-Disposition: attachement; filename="license_manager__plugin_settings_' . date("__d_m_Y__H_i_s"). '.fslmsettings";');
2097 echo $this->generate_plugin_settings();
2098 die();
2099 }
2100
2101 /*****************/
2102 // Admin Notifications
2103 /*****************/
2104 public function admin_notifications(){
2105 global $wp_admin_bar;
2106 global $wpdb;
2107 global $wp_query;
2108 global $woocommerce;
2109
2110 $temp_query = clone $wp_query;
2111
2112 $args = array();
2113
2114 $products_args = array('post_type' => 'product', 'posts_per_page' => -1);
2115
2116 $loop = get_posts($products_args);
2117
2118 $to = get_option('fslm_notif_mail_to');
2119 $subject = __('License Keys stock running low', 'fslm');
2120 $message = '';
2121 $headers = "MIME-Version: 1.0" . PHP_EOL;
2122 $headers .= "Content-Type: text/html; charset=UTF-8" . PHP_EOL;
2123 $nb_ramaining_keys = -1;
2124 $nb_var_ramaining_keys = -1;
2125 $isVariation = false;
2126 $send_mail = false;
2127 $c = 0;
2128 foreach($loop as $post){
2129
2130 $porduct_name = $post->post_title;
2131 $nb_ramaining_keys = $wpdb->get_var("SELECT COUNT(*)FROM {$wpdb->prefix}wc_fs_product_licenses_keys WHERE product_id='" . $post->ID . "' AND license_status='available'");
2132
2133 $handle = new WC_Product_Variable($post->ID);
2134
2135 $variations = $handle->get_children();
2136 foreach($variations as $variation){
2137
2138 $nb_var_ramaining_keys = $wpdb->get_var("SELECT COUNT(*)FROM {$wpdb->prefix}wc_fs_product_licenses_keys WHERE product_id='" . $post->ID . "' AND variation_id = '" . $variation . "' AND license_status='available'");
2139
2140 $licensable =($this->is_licensing_enabled($post->ID, $variation)&&(!$this->isGeneratorActive($post->ID, $variation)));
2141
2142 if(($licensable) && ((int)$nb_var_ramaining_keys <(int)get_option('fslm_notif_min_licenses_nb', '10'))){
2143
2144 $single_variation = new WC_Product_Variation($variation);
2145
2146 $id = 'fslm_notif_' . $c;
2147 $title = __('Please add license keys for Product variation', 'fslm'). ' ' . $porduct_name . ' ' . $single_variation->get_formatted_name(). ', ' . $nb_var_ramaining_keys . ' ' . __('License Key left' ,'fslm');
2148
2149 $message .= $title . '<br>';
2150
2151 array_push($args,array(
2152 'id' => $id,
2153 'title' => $title,
2154 'parent' => 'fslm_notifications',
2155 'meta' => array(
2156 'class' => 'fslm_warning'
2157 )
2158 ));
2159
2160 $send_mail = true;
2161 $c++;
2162 $isVariation = true;
2163 }
2164
2165 }
2166
2167 $licensable =($this->is_licensing_enabled($post->ID)&&(!$this->isGeneratorActive($post->ID)));
2168
2169 if(($licensable) && (!$isVariation &&(int)$nb_ramaining_keys <(int)get_option('fslm_notif_min_licenses_nb', '10'))){
2170
2171 $id = 'fslm_notif_' . $c;
2172 $title = __('Please add license keys for', 'fslm'). ' ' . $porduct_name . ', ' . $nb_ramaining_keys . ' ' . __('License Key left' ,'fslm');
2173
2174 $message .= $title . '<br>';
2175
2176 array_push($args, array(
2177 'id' => $id,
2178 'title' => $title,
2179 'parent' => 'fslm_notifications',
2180 'meta' => array(
2181 'class' => 'fslm_warning'
2182 )
2183 ));
2184
2185 $send_mail = true;
2186 $c++;
2187 }
2188 $isVariation = false;
2189
2190
2191 }
2192
2193 wp_reset_query();
2194
2195 if(is_admin()){
2196
2197 $title = __('License Manager', 'fslm'). ' <span class="fslm_nb_notif">' . $c . '</span>';
2198
2199 $wp_admin_bar->add_node(array(
2200 'id' => 'fslm_notifications',
2201 'title' => $title,
2202 'meta' => array('class' => 'first-toolbar-group'),
2203 ));
2204
2205 if($c == 0) {
2206 array_push($args, array(
2207 'id' => 'fslm-no-notifications',
2208 'title' => __('There is no notifications', 'fslm'),
2209 'parent' => 'fslm_notifications',
2210 'meta' => array(
2211 'class' => 'fslm_warning'
2212 )
2213 ));
2214
2215 $c++;
2216 }
2217
2218 for($i=0; $i<$c; $i++){
2219 $wp_admin_bar->add_node($args[$i]);
2220 }
2221
2222 }
2223
2224 $wp_query = clone $temp_query;
2225
2226
2227 if(($send_mail)&&(get_option('fslm_notif_mail')== 'on')&&((time()-(60*60*24))> get_option('fslm_last_sent_notification_email_date', '0'))){
2228
2229 $headers = apply_filters('woocommerce_email_headers', '', 'rewards_message');
2230 $attachments = array();
2231
2232 $heading = __('Please add more license key for the following items', 'fslm');
2233
2234 $mailer = $woocommerce->mailer();
2235 $message = $mailer->wrap_message($heading, $message);
2236
2237 $mailer->send($to, $subject, $message, $headers, array());
2238
2239 update_option('fslm_last_sent_notification_email_date', time());
2240 }
2241
2242 }
2243
2244 /*****************/
2245 // Save product license settings
2246 /*****************/
2247 public function fslm_save_metabox_callback(){
2248 global $wpdb;
2249
2250 $product_id = $_POST['mbs_product_id'];
2251
2252 $software_name = $_POST['fslm_sn'];
2253 $software_ID = $_POST['fslm_sid'];
2254 $software_version = $_POST['fslm_sv'];
2255 $software_author = $_POST['fslm_sa'];
2256 $software_url = $_POST['fslm_surl'];
2257 $software_last_update = $_POST['fslm_slu'];
2258 $software_extra_data = $_POST['fslm_sed'];
2259
2260 if(!add_post_meta((int)$product_id, 'fslm_sn', $software_name, true)){
2261 update_post_meta((int)$product_id, 'fslm_sn', $software_name);
2262 }
2263
2264 if(!add_post_meta((int)$product_id, 'fslm_sid', $software_ID, true)){
2265 update_post_meta((int)$product_id, 'fslm_sid', $software_ID);
2266 }
2267
2268 if(!add_post_meta((int)$product_id, 'fslm_sv', $software_version, true)){
2269 update_post_meta((int)$product_id, 'fslm_sv', $software_version);
2270 }
2271
2272 if(!add_post_meta((int)$product_id, 'fslm_sa', $software_author, true)){
2273 update_post_meta((int)$product_id, 'fslm_sa', $software_author);
2274 }
2275
2276 if(!add_post_meta((int)$product_id, 'fslm_surl', $software_url, true)){
2277 update_post_meta((int)$product_id, 'fslm_surl', $software_url);
2278 }
2279
2280 if(!add_post_meta((int)$product_id, 'fslm_slu', $software_last_update, true)){
2281 update_post_meta((int)$product_id, 'fslm_slu', $software_last_update);
2282 }
2283
2284 if(!add_post_meta((int)$product_id, 'fslm_sed', $software_extra_data, true)){
2285 update_post_meta((int)$product_id, 'fslm_sed', $software_extra_data);
2286 }
2287
2288 $licensable = $_POST['mbs_licensable'];
2289 $variation_id = $_POST['mbs_variation_id'];
2290 $active = $_POST['mbs_active'] == 'true'?'1':'0';
2291 $prefix = $_POST['mbs_prefix'];
2292 $chunks_number = $_POST['mbs_chunks_number'];
2293 $chunks_length = $_POST['mbs_chunks_length'];
2294 $suffix = $_POST['mbs_suffix'];
2295 $max_instance_number = $_POST['mbs_max_instance_number'];
2296 $valid = $_POST['mbs_valid'];
2297
2298 $this->set_licensing($product_id, '0', $licensable);
2299
2300
2301 $handle = new WC_Product_Variable($product_id);
2302
2303 $variations = $handle->get_children();
2304 foreach ($variations as $variation) {
2305 $single_variation = new WC_Product_Variation($variation);
2306 $licensable_variation = $_POST["mbs_licensable_{$variation}"];
2307
2308 $this->set_licensing($product_id, $variation, $licensable_variation);
2309 }
2310
2311 $show_in = $_POST['fslm_show_in'];
2312 $display = $_POST['fslm_display'];
2313
2314 if(!add_post_meta((int)$product_id, 'fslm_show_in', $show_in, true)){
2315 update_post_meta((int)$product_id, 'fslm_show_in', $show_in);
2316 }
2317
2318 if(!add_post_meta((int)$product_id, 'fslm_display', $display, true)){
2319 update_post_meta((int)$product_id, 'fslm_display', $display);
2320 }
2321
2322 $this->set_licensing($product_id, $variation_id, $licensable);
2323
2324 $nb_delivered_lk = $_POST['fslm_nb_delivered_lk'];
2325
2326 if(!add_post_meta((int)$product_id, 'fslm_nb_delivered_lk', $nb_delivered_lk, true)){
2327 update_post_meta((int)$product_id, 'fslm_nb_delivered_lk', $nb_delivered_lk);
2328 }
2329
2330 $data = array(
2331 'product_id' => $product_id,
2332 'variation_id' => $variation_id,
2333 'prefix' => $prefix,
2334 'chunks_number' => $chunks_number,
2335 'chunks_length' => $chunks_length,
2336 'suffix' => $suffix,
2337 'max_instance_number' => $max_instance_number,
2338 'valid' => $valid,
2339 'active' => $active
2340 );
2341
2342 $exist =(int)$wpdb->get_var("SELECT COUNT(*)FROM {$wpdb->prefix}wc_fs_product_licenses_keys_generator_rules WHERE product_id = '" . $product_id . "' and variation_id = '" . $variation_id . "'");
2343
2344 if($exist == 0){
2345 $wpdb->insert("{$wpdb->prefix}wc_fs_product_licenses_keys_generator_rules", $data);
2346 }else {
2347 $where = array(
2348 'product_id' => $product_id,
2349 'variation_id' => $variation_id
2350 );
2351
2352 $wpdb->update("{$wpdb->prefix}wc_fs_product_licenses_keys_generator_rules", $data, $where);
2353 }
2354
2355 echo "Saved";
2356 die();
2357 }
2358
2359 /*****************/
2360 // Add License ajax Callback
2361 /*****************/
2362 public function add_license_ajax_callback(){
2363 global $wpdb;
2364
2365 $product_id = $_POST['alk_product_id'];
2366 $license_key = $this->newLine2br($_POST['alk_license_key']);
2367 if(! $this->license_key_existe($license_key)){
2368 $variation_id = $_REQUEST['alk_variation_id'];
2369 $max_instance_number =(int)$_REQUEST['alk_max_instance_number'];
2370 $yy =(int)$_REQUEST['alk_xpdyear'];
2371 $mm =(int)$_REQUEST['alk_xpdmonth'];
2372 $dd =(int)$_REQUEST['alk_xpdday'];
2373 $valid =(int)$_REQUEST['alk_valid'];
2374 $image_license_key = '';
2375
2376
2377 $deliver_x_times =(int)$_REQUEST['alk_deliver_x_times'];
2378
2379
2380 if(!empty($_FILES["alk_image_license_key"]['name'])){
2381 $upload_directory = wp_upload_dir();
2382 $target_dir = $upload_directory['basedir'] . '/fslm_keys/';
2383 if(!file_exists($target_dir)){
2384 wp_mkdir_p($target_dir);
2385 $fp = fopen($target_dir . 'index.php', 'w');
2386 fwrite($fp, '<?php');
2387 fclose($fp);
2388 }
2389
2390 $imageFileType = strtolower(pathinfo($_FILES["alk_image_license_key"]["name"], PATHINFO_EXTENSION));
2391 $file_name = basename(uniqid(). '.' . $imageFileType);
2392 $target_file = $target_dir . $file_name;
2393 $image_license_key = $file_name;
2394 $uploadOk = 1;
2395
2396 // Check if image file is a actual image or fake image
2397
2398 $check = getimagesize($_FILES["alk_image_license_key"]["tmp_name"]);
2399 $uploadOk =($check !== false)? 1 : 0;
2400
2401 // Check if file already exists
2402 while(file_exists($target_file)){
2403 $file_name = basename(uniqid(). '.' . $imageFileType);
2404 $target_file = $target_dir . $file_name;
2405 $image_license_key = $file_name;
2406 }
2407 // Check file size
2408 if($_FILES["alk_image_license_key"]["size"] > 10 * MB){
2409 $uploadOk = 0;
2410 }
2411 // Allow certain file formats
2412 $allowed_formats = array('jpg', 'png', 'jpeg', 'gif');
2413 if(!in_array($imageFileType, $allowed_formats)){
2414 $uploadOk = 0;
2415 }
2416 // Check if $uploadOk is set to 0 by an error
2417 if($uploadOk == 0){
2418 echo "Sorry, your file was not uploaded.";
2419 // if everything is ok, try to upload file
2420 } else {
2421 if(move_uploaded_file($_FILES["alk_image_license_key"]["tmp_name"], $target_file)){
2422 echo "The file " . basename($_FILES["alk_image_license_key"]["name"]). " has been uploaded.";
2423 } else {
2424 echo "Sorry, there was an error uploading your file.";
2425 }
2426 }
2427 }
2428
2429 $license_key = $this->encrypt_decrypt('encrypt', $license_key, ENCRYPTION_KEY, ENCRYPTION_VI);
2430
2431 $data = array(
2432 'product_id' => $product_id,
2433 'variation_id' => $variation_id,
2434 'license_key' => $license_key,
2435 'image_license_key' => $image_license_key,
2436 'delivre_x_times' => $deliver_x_times,
2437 'remaining_delivre_x_times' => $deliver_x_times,
2438 'max_instance_number' => $max_instance_number,
2439 'number_use_remaining' => $max_instance_number,
2440 'creation_date' => date('Y-m-d H:i:s'),
2441 'expiration_date' => $yy . '-' . $mm . '-' . $dd . ' 0:0:0',
2442 'valid' => $valid,
2443 'license_status' => 'available'
2444 );
2445 $variation = wc_get_product( $variation_id );
2446 $variation->set_stock_quantity($variation->get_stock_quantity() + 1);
2447 $variation->save();
2448 $wpdb->insert("{$wpdb->prefix}wc_fs_product_licenses_keys", $data);
2449 }
2450
2451 require_once('includes/metabox_licenses_list.php');
2452
2453 echo fslm_metabox_licenses_list($product_id);
2454
2455 die();
2456 }
2457
2458 /*****************/
2459 // Plugins initial settings
2460 /*****************/
2461 public function activate(){
2462 global $wpdb;
2463 $query = array();
2464 $query[] = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}wc_fs_product_licenses_keys(
2465 license_id int(11)NOT NULL AUTO_INCREMENT,
2466 product_id int(11)NOT NULL,
2467 variation_id int(11)NOT NULL,
2468 license_key text DEFAULT NULL,
2469 image_license_key text(1000) DEFAULT NULL,
2470 license_status text(1000) DEFAULT NULL,
2471 owner_first_name text(1000)DEFAULT NULL,
2472 owner_last_name text(1000)DEFAULT NULL,
2473 owner_email_address text(1000)DEFAULT NULL,
2474 delivre_x_times int(11)DEFAULT NULL,
2475 remaining_delivre_x_times int(11)DEFAULT NULL,
2476 max_instance_number int(11)DEFAULT NULL,
2477 number_use_remaining int(11)DEFAULT NULL,
2478 activation_date date DEFAULT NULL,
2479 creation_date date DEFAULT NULL,
2480 expiration_date date DEFAULT NULL,
2481 valid int(11)NOT NULL,
2482 PRIMARY KEY(license_id)
2483 )";
2484
2485 $query[] = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}wc_fs_licensed_products(
2486 config_id int(11)NOT NULL AUTO_INCREMENT,
2487 product_id int(11)NOT NULL,
2488 variation_id int(11)NOT NULL,
2489 active tinyint(1)NOT NULL,
2490 PRIMARY KEY(config_id),
2491 UNIQUE KEY product_id(product_id, variation_id)
2492 )";
2493
2494 $query[] = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}wc_fs_product_licenses_keys_generator_rules(
2495 rule_id int(11)NOT NULL AUTO_INCREMENT,
2496 product_id int(11)NOT NULL,
2497 variation_id int(11)NOT NULL,
2498 prefix varchar(100)DEFAULT NULL,
2499 chunks_number int(11)NOT NULL,
2500 chunks_length int(11)NOT NULL,
2501 suffix varchar(100)DEFAULT NULL,
2502 max_instance_number int(11)DEFAULT NULL,
2503 valid int(11)DEFAULT NULL,
2504 active tinyint(1)NOT NULL,
2505 PRIMARY KEY(rule_id),
2506 UNIQUE KEY product_id(product_id, variation_id)
2507 )";
2508
2509 foreach($query as $q){
2510 $wpdb->query($q);
2511 }
2512
2513 add_option('fslm_nb_rows_by_page', '15');
2514 add_option('fslm_show_adminbar_notifs', 'on');
2515 add_option('fslm_guest_customer', 'on');
2516 add_option('fslm_enable_cart_validation', '');
2517 add_option('fslm_meta_key_name', 'License Key');
2518 add_option('fslm_generator_chars', '0123456789ABCDEF');
2519 add_option('fslm_meta_key_name_plural', 'License Keys');
2520
2521 add_option('fslm_send_when_completed', 'on');
2522 add_option('fslm_send_when_processing', 'on');
2523
2524 add_option('fslm_prefix', '');
2525 add_option('fslm_chunks_number', '4');
2526 add_option('fslm_chunks_length', '4');
2527 add_option('fslm_suffix', '');
2528 add_option('fslm_max_instance_number', '1');
2529 add_option('fslm_valid', '0');
2530
2531 add_option('fslm_active', '0');
2532
2533
2534 add_option('fslm_notif_min_licenses_nb', '10');
2535 add_option('fslm_notif_mail', 'off');
2536 add_option('fslm_notif_mail_to', '');
2537
2538
2539 add_option('fslm_last_sent_notification_email_date', '0');
2540 add_option('fslm_page_id', '-1');
2541
2542
2543 $page_id = get_option('fslm_page_id', '-1');
2544 if($page_id == '-1') {
2545
2546 if(!is_page($page_id)) {
2547 $license_keys_page = array(
2548 'post_title' => __('License Key', 'fslm'),
2549 'post_content' => '[license_keys]',
2550 'post_status' => 'publish',
2551 'post_type' => 'page',
2552 'post_author' => 1,
2553 'post_date' => date('Y-m-d H:i:s')
2554 );
2555
2556 $page_id = wp_insert_post($license_keys_page);
2557
2558 update_option('fslm_page_id', $page_id);
2559 }
2560
2561 }
2562
2563 }
2564
2565 function activation_redirect($plugin) {
2566 if($plugin == plugin_basename(__FILE__)) {
2567 exit(wp_redirect(admin_url('admin.php?page=license-manager-welcome')));
2568 }
2569 }
2570
2571 function is_licensed($product_id, $variation_id = 0) {
2572 global $wpdb;
2573 return $wpdb->get_var("SELECT COUNT(active) FROM {$wpdb->prefix}wc_fs_licensed_products WHERE product_id = '{$product_id}' AND variation_id = '{$variation_id}'")==0?false:true;
2574 }
2575
2576 function is_licensing_enabled($product_id, $variation_id = 0) {
2577 global $wpdb;
2578 return $wpdb->get_var("SELECT active FROM {$wpdb->prefix}wc_fs_licensed_products WHERE product_id = '{$product_id}' AND variation_id = '{$variation_id}' AND active = '1'")=='1'?true:false;
2579 }
2580
2581 function set_licensing($product_id, $variation_id, $active) {
2582 global $wpdb;
2583
2584 if($this->is_licensed($product_id, $variation_id)) {
2585 $data = array(
2586 'active' => $active
2587 );
2588
2589 $where = array(
2590 'product_id' => $product_id,
2591 'variation_id' => $variation_id
2592 );
2593
2594 $wpdb->update("{$wpdb->prefix}wc_fs_licensed_products", $data, $where);
2595
2596 }else{
2597 $data = array(
2598 'product_id' => $product_id,
2599 'variation_id' => $variation_id,
2600 'active' => $active
2601 );
2602
2603 $wpdb->insert("{$wpdb->prefix}wc_fs_licensed_products", $data);
2604 }
2605 }
2606
2607 public function deactivate(){
2608 global $wpdb;
2609 $query = array();
2610
2611 if(get_option('fslm_delete_lk_db_tables', '')=='on') {
2612
2613 $query[] = "DROP TABLE {$wpdb->prefix}wc_fs_product_licenses_keys";
2614
2615 }
2616
2617 if(get_option('fslm_delete_gr_db_tables', '')=='on') {
2618
2619 $query[] = "DROP TABLE {$wpdb->prefix}wc_fs_product_licenses_keys_generator_ruless";
2620
2621 }
2622
2623 if(get_option('fslm_delete_lp_db_tables', '')=='on') {
2624
2625 $query[] = "DROP TABLE {$wpdb->prefix}wc_fs_licensed_products";
2626
2627 }
2628
2629 foreach($query as $q){
2630 $wpdb->query($q);
2631 }
2632 }
2633
2634 /*****************/
2635 // Add Product page License Manager metabox
2636 /*****************/
2637 public function action_add_metaboxes(){
2638 add_meta_box('fslm-wc-licenses', __('License', 'fslm'), array($this, 'metabox_licenses'), 'product', 'advanced');
2639 }
2640
2641 /*****************/
2642 // Product page License Manager metabox
2643 /*****************/
2644 public function metabox_licenses(){
2645 require dirname(__FILE__). '/includes/product_metabox.php';
2646 }
2647
2648 /*****************/
2649 // Admin Requests Handler
2650 /*****************/
2651 public function requestHandler(){
2652 global $wpdb;
2653
2654 $action = isset($_REQUEST['action'])? $_REQUEST['action'] : null;
2655 if(!$action)
2656 return false;
2657
2658 if($action == 'delete_license'){
2659 $this->delete_license();
2660
2661 }else if($action == 'delete_rule'){
2662 $this->delete_rule();
2663
2664 }else if($action == 'add_license'){
2665 $this->add_license();
2666
2667 }else if($action == 'add_rule'){
2668 $this->add_rule();
2669
2670 }else if($action == 'edit_rule'){
2671 $this->edit_rule();
2672
2673 }else if($action == 'edit_license'){
2674 $this->edit_license();
2675
2676 }else if($action == 'licenses_bulk_action'){
2677 $this->licenses_bulk_action();
2678
2679 }else if($action == 'generator_bulk_action'){
2680 $this->generator_bulk_action();
2681 }else if($action == 'save_encryption_setting'){
2682 $this->save_encryption_setting();
2683 }
2684 }
2685
2686 function save_encryption_setting() {
2687
2688 $key = $_POST['fslm_encryption_key'];
2689 $vi = $_POST['fslm_encryption_vi'];
2690
2691 $this->set_encryption_key($key, $vi, 'update');
2692
2693 $link = admin_url('admin.php?page=license-manager-settings&tab=encryption');
2694 wp_redirect($link);
2695 die();
2696 }
2697
2698 /*****************/
2699 // Add License
2700 /*****************/
2701 function add_license(){
2702 global $wpdb;
2703
2704 $license_key = $this->newLine2br($_POST['license_key']);
2705
2706 $license_key = $this->encrypt_decrypt('encrypt', $license_key, ENCRYPTION_KEY, ENCRYPTION_VI);
2707
2708 if(! $this->license_key_existe($license_key)){
2709 $product_id = $_REQUEST['product_id'];
2710 $variation_id = $_REQUEST['variation_id'];
2711
2712 $max_instance_number =(int)$_REQUEST['max_instance_number'];
2713 $yy =(int)$_REQUEST['yy'];
2714 $mm =(int)$_REQUEST['mm'];
2715 $dd =(int)$_REQUEST['dd'];
2716 $valid =(int)$_REQUEST['valid'];
2717 $image_license_key = '';
2718
2719 $deliver_x_times =(int)$_REQUEST['deliver_x_times'];
2720
2721
2722 if(!empty($_FILES["image_license_key"]['name'])){
2723 $upload_directory = wp_upload_dir();
2724 $target_dir = $upload_directory['basedir'] . '/fslm_keys/';
2725 if(!file_exists($target_dir)){
2726 wp_mkdir_p($target_dir);
2727 $fp = fopen($target_dir . 'index.php', 'w');
2728 fwrite($fp, '<?php');
2729 fclose($fp);
2730 }
2731
2732 $imageFileType = strtolower(pathinfo($_FILES["image_license_key"]["name"], PATHINFO_EXTENSION));
2733 $file_name = basename(uniqid(). '.' . $imageFileType);
2734 $target_file = $target_dir . $file_name;
2735 $image_license_key = $file_name;
2736 $uploadOk = 1;
2737
2738 // Check if image file is a actual image or fake image
2739
2740 $check = getimagesize($_FILES["image_license_key"]["tmp_name"]);
2741 $uploadOk =($check !== false)? 1 : 0;
2742
2743 // Check if file already exists
2744 while(file_exists($target_file)){
2745 $file_name = basename(uniqid(). '.' . $imageFileType);
2746 $target_file = $target_dir . $file_name;
2747 $image_license_key = $file_name;
2748 }
2749 // Check file size
2750 if($_FILES["image_license_key"]["size"] > 10 * MB){
2751 $uploadOk = 0;
2752 }
2753 // Allow certain file formats
2754 $allowed_formats = array('jpg', 'png', 'jpeg', 'gif');
2755 if(!in_array($imageFileType, $allowed_formats)){
2756 $uploadOk = 0;
2757 }
2758 // Check if $uploadOk is set to 0 by an error
2759 if($uploadOk == 0){
2760 echo "Sorry, your file was not uploaded.";
2761 // if everything is ok, try to upload file
2762 } else {
2763 if(move_uploaded_file($_FILES["image_license_key"]["tmp_name"], $target_file)){
2764 echo "The file " . basename($_FILES["image_license_key"]["name"]). " has been uploaded.";
2765 } else {
2766 echo "Sorry, there was an error uploading your file.";
2767 }
2768 }
2769 }
2770
2771 $data = array(
2772 'product_id' => $product_id,
2773 'variation_id' => $variation_id,
2774 'license_key' => $license_key,
2775 'image_license_key' => $image_license_key,
2776 'delivre_x_times' => $deliver_x_times,
2777 'remaining_delivre_x_times' => $deliver_x_times,
2778 'max_instance_number' => $max_instance_number,
2779 'number_use_remaining' => $max_instance_number,
2780 'creation_date' => date('Y-m-d H:i:s'),
2781 'expiration_date' => $yy . '-' . $mm . '-' . $dd . ' 0:0:0',
2782 'valid' => $valid,
2783 'license_status' => 'available'
2784 );
2785 $variation = wc_get_product( $variation_id );
2786 $variation->set_stock_quantity($variation->get_stock_quantity() + 1);
2787 $variation->save();
2788 $wpdb->insert("{$wpdb->prefix}wc_fs_product_licenses_keys", $data);
2789 }
2790
2791 $link = admin_url('admin.php?page=license-manager');
2792 wp_redirect($link);
2793 die();
2794
2795 }
2796
2797 function license_key_existe($license_key){
2798 global $wpdb;
2799
2800 $query = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}wc_fs_product_licenses_keys WHERE license_key='" . $license_key . "'");
2801
2802 if($query){
2803 return true;
2804 }
2805
2806 return false;
2807
2808 }
2809
2810 /*****************/
2811 // Edit License
2812 /*****************/
2813 function edit_license(){
2814 global $wpdb;
2815
2816 $license_key = $this->newLine2br($_POST['license_key']);
2817
2818 $license_key = $this->encrypt_decrypt('encrypt', $license_key, ENCRYPTION_KEY, ENCRYPTION_VI);
2819
2820 $license_id = $_REQUEST['license_id'];
2821 $product_id = $_REQUEST['product_id'];
2822 $variation_id = $_REQUEST['variation_id'];
2823 $max_instance_number = $_REQUEST['max_instance_number'];
2824 $number_use_remaining =(int)$_REQUEST['number_use_remaining'];
2825
2826 $owner_first_name = $_REQUEST['owner_first_name'];
2827 $owner_last_name = $_REQUEST['owner_last_name'];
2828 $owner_email_address = $_REQUEST['owner_email_address'];
2829
2830 $creation_day =(int)$_REQUEST['creation_day'];
2831 $creation_month =(int)$_REQUEST['creation_month'];
2832 $creation_year =(int)$_REQUEST['creation_year'];
2833
2834 $activation_day =(int)$_REQUEST['activation_day'];
2835 $activation_month =(int)$_REQUEST['activation_month'];
2836 $activation_year =(int)$_REQUEST['activation_year'];
2837
2838 $expiration_day =(int)$_REQUEST['expiration_day'];
2839 $expiration_month =(int)$_REQUEST['expiration_month'];
2840 $expiration_year =(int)$_REQUEST['expiration_year'];
2841
2842 $valid =(int)$_REQUEST['valid'];
2843
2844 $license_status = $_REQUEST['status'];
2845
2846 $deliver_x_times =(int)$_REQUEST['deliver_x_times'];
2847 $remaining_delivre_x_times =(int)$_REQUEST['remaining_delivre_x_times'];
2848
2849
2850 $image_license_key = $this->get_image_name($license_id);
2851 if((isset($_REQUEST['rmoi']) && $_REQUEST['rmoi'] == 'on')&&($image_license_key != '')){
2852 $this->delete_image($image_license_key);
2853
2854 $image_license_key = '';
2855 }
2856
2857 if(!empty($_FILES["image_license_key"]['name'])){
2858 if((isset($_REQUEST['rmoi']) && $_REQUEST['rmoi'])&&($image_license_key != '')){
2859 $this->delete_image($image_license_key);
2860
2861 $image_license_key = '';
2862 }
2863 $upload_directory = wp_upload_dir();
2864 $target_dir = $upload_directory['basedir'] . '/fslm_keys/';
2865 if(!file_exists($target_dir)){
2866 wp_mkdir_p($target_dir);
2867 $fp = fopen($target_dir . 'index.php', 'w');
2868 fwrite($fp, '<?php');
2869 fclose($fp);
2870 }
2871
2872 $imageFileType = strtolower(pathinfo($_FILES["image_license_key"]["name"], PATHINFO_EXTENSION));
2873 $file_name = basename(uniqid(). '.' . $imageFileType);
2874 $target_file = $target_dir . $file_name;
2875 $image_license_key = $file_name;
2876 $uploadOk = 1;
2877
2878 // Check if image file is a actual image or fake image
2879
2880 $check = getimagesize($_FILES["image_license_key"]["tmp_name"]);
2881 $uploadOk =($check !== false)? 1 : 0;
2882
2883 // Check if file already exists
2884 while(file_exists($target_file)){
2885 $file_name = basename(uniqid(). '.' . $imageFileType);
2886 $target_file = $target_dir . $file_name;
2887 $image_license_key = $file_name;
2888 }
2889 // Check file size
2890 if($_FILES["image_license_key"]["size"] > 10 * MB){
2891 $uploadOk = 0;
2892 }
2893 // Allow certain file formats
2894 $allowed_formats = array('jpg', 'png', 'jpeg', 'gif');
2895 if(!in_array($imageFileType, $allowed_formats)){
2896 $uploadOk = 0;
2897 }
2898 // Check if $uploadOk is set to 0 by an error
2899 if($uploadOk == 0){
2900 echo "Sorry, your file was not uploaded.";
2901 // if everything is ok, try to upload file
2902 } else {
2903 if(move_uploaded_file($_FILES["image_license_key"]["tmp_name"], $target_file)){
2904 echo "The file " . basename($_FILES["image_license_key"]["name"]). " has been uploaded.";
2905 } else {
2906 echo "Sorry, there was an error uploading your file.";
2907 }
2908 }
2909 }
2910
2911 $data = array(
2912 'product_id' => $product_id,
2913 'variation_id' => $variation_id,
2914 'license_key' => $license_key,
2915 'image_license_key' => $image_license_key,
2916 'delivre_x_times' => $deliver_x_times,
2917 'remaining_delivre_x_times' => $remaining_delivre_x_times,
2918 'max_instance_number' => $max_instance_number,
2919 'number_use_remaining' => $number_use_remaining,
2920 'owner_first_name' => $owner_first_name,
2921 'owner_last_name' => $owner_last_name,
2922 'owner_email_address' => $owner_email_address,
2923 'creation_date' => $creation_year . '-' . $creation_month . '-' . $creation_day . ' 0:0:0',
2924 'activation_date' => $activation_year . '-' . $activation_month . '-' . $activation_day . ' 0:0:0',
2925 'expiration_date' => $expiration_year . '-' . $expiration_month . '-' . $expiration_day . ' 0:0:0',
2926 'valid' => $valid,
2927 'license_status' => $license_status
2928 );
2929
2930 $where = array(
2931 'license_id' => $license_id
2932 );
2933 $wpdb->update("{$wpdb->prefix}wc_fs_product_licenses_keys", $data, $where);
2934
2935 $link = admin_url('admin.php?page=license-manager');
2936 wp_redirect($link);
2937 die();
2938 }
2939
2940 function get_image_name($license_id){
2941 global $wpdb;
2942
2943 $query = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}wc_fs_product_licenses_keys WHERE license_id='" . $license_id . "'");
2944
2945 if($query){
2946 $query = $query[0];
2947
2948 return $query->image_license_key;
2949 }
2950
2951 return '';
2952 }
2953
2954 function delete_image($file){
2955 $upload_directory = wp_upload_dir();
2956 $target_file = $upload_directory['basedir'] . '/fslm_keys/' . $file;
2957 if(file_exists($target_file)){
2958 chmod($target_file, 0777);
2959 unlink($target_file);
2960 }
2961 }
2962
2963 /*****************/
2964 // Delete License
2965 /*****************/
2966 function delete_license(){
2967 global $wpdb;
2968 $wpdb->delete($wpdb->prefix . 'wc_fs_product_licenses_keys', array('license_id' =>(int)$_REQUEST['license_id']));
2969
2970 $image_license_key = $this->get_image_name((int)$_REQUEST['license_id']);
2971 if($image_license_key != ''){
2972 $this->delete_image($image_license_key);
2973 }
2974
2975 $link = admin_url('admin.php?page=license-manager');
2976 wp_redirect($link);
2977 die();
2978 }
2979
2980 /*****************/
2981 // Add Generator rule
2982 /*****************/
2983 function add_rule(){
2984 global $wpdb;
2985
2986 $product_id = $_REQUEST['product_id'];
2987 $variation_id = $_REQUEST['variation_id'];
2988 $prefix = $_REQUEST['prefix'];
2989 $chunks_number =(int)$_REQUEST['chunks_number'];
2990 $chunks_length =(int)$_REQUEST['chunks_length'];
2991 $suffix = $_REQUEST['suffix'];
2992 $max_instance_number = $_REQUEST['max_instance_number'];
2993 $valid = $_REQUEST['valid'];
2994 $active =(int)$_REQUEST['active'];
2995
2996
2997 $data = array(
2998 'product_id' => $product_id,
2999 'variation_id' => $variation_id,
3000 'prefix' => $prefix,
3001 'chunks_number' => $chunks_number,
3002 'chunks_length' => $chunks_length,
3003 'suffix' => $suffix,
3004 'max_instance_number' => $max_instance_number,
3005 'valid' => $valid,
3006 'active' => $active
3007 );
3008 $wpdb->insert("{$wpdb->prefix}wc_fs_product_licenses_keys_generator_rules", $data);
3009 $link = admin_url('admin.php?page=license-manager-license-key-generator');
3010 wp_redirect($link);
3011 die();
3012
3013 }
3014
3015 /*****************/
3016 // Edit Generator rule
3017 /*****************/
3018 function edit_rule(){
3019 global $wpdb;
3020
3021 $rule_id = $_REQUEST['rule_id'];
3022 $product_id = $_REQUEST['product_id'];
3023 $variation_id = $_REQUEST['variation_id'];
3024 $prefix = $_REQUEST['prefix'];
3025 $chunks_number =(int)$_REQUEST['chunks_number'];
3026 $chunks_length =(int)$_REQUEST['chunks_length'];
3027 $suffix = $_REQUEST['suffix'];
3028 $max_instance_number = $_REQUEST['max_instance_number'];
3029 $valid = $_REQUEST['valid'];
3030 $active =(int)$_REQUEST['active'];
3031
3032 $data = array(
3033 'product_id' => $product_id,
3034 'variation_id' => $variation_id,
3035 'prefix' => $prefix,
3036 'chunks_number' => $chunks_number,
3037 'chunks_length' => $chunks_length,
3038 'suffix' => $suffix,
3039 'max_instance_number' => $max_instance_number,
3040 'valid' => $valid,
3041 'active' => $active
3042 );
3043 $where = array(
3044 'rule_id' => $rule_id
3045 );
3046 $wpdb->update("{$wpdb->prefix}wc_fs_product_licenses_keys_generator_rules", $data, $where);
3047 $link = admin_url('admin.php?page=license-manager');
3048 wp_redirect($link);
3049 die();
3050 }
3051
3052 /*****************/
3053 // Delete Generator rule
3054 /*****************/
3055 function delete_rule(){
3056 global $wpdb;
3057 $wpdb->delete($wpdb->prefix . 'wc_fs_product_licenses_keys_generator_rules', array('rule_id' =>(int)$_REQUEST['rule_id']));
3058 $link = admin_url('admin.php?page=license-manager');
3059 wp_redirect($link);
3060 die();
3061 }
3062
3063 /*****************/
3064 // Licenses Bulk action Handler
3065 /*****************/
3066 function licenses_bulk_action(){
3067 global $wpdb;
3068
3069 if(!isset($_POST['post'])) {
3070 $link = admin_url('admin.php?page=license-manager');
3071 wp_redirect($link);
3072
3073 die();
3074 }
3075
3076 if($_POST['baction'] == 'trash'){
3077
3078 $ids = $_POST['post'];
3079
3080 $sql = "DELETE FROM {$wpdb->prefix}wc_fs_product_licenses_keys WHERE license_id IN([IN])";
3081 $sql = $this->prepare_in($sql, $ids);
3082
3083 $wpdb->query($sql);
3084
3085 foreach($ids as $id){
3086 $image_license_key = $this->get_image_name($id);
3087 if($image_license_key != ''){
3088 $this->delete_image($image_license_key);
3089 }
3090 }
3091
3092 }else if($_POST['baction'] == 'available'){
3093
3094 $ids = $_POST['post'];
3095
3096 $sql = "UPDATE {$wpdb->prefix}wc_fs_product_licenses_keys SET license_status = 'available', remaining_delivre_x_times = 1, delivre_x_times = 1 WHERE license_id IN([IN])";
3097 $sql = $this->prepare_in($sql, $ids);
3098
3099 $wpdb->query($sql);
3100
3101 }else if($_POST['baction'] == 'active'){
3102
3103 $ids = $_POST['post'];
3104
3105 $sql = "UPDATE {$wpdb->prefix}wc_fs_product_licenses_keys SET license_status = 'active' WHERE license_id IN([IN])";
3106 $sql = $this->prepare_in($sql, $ids);
3107
3108 $wpdb->query($sql);
3109
3110 }else if($_POST['baction'] == 'expired'){
3111
3112 $ids = $_POST['post'];
3113
3114 $sql = "UPDATE {$wpdb->prefix}wc_fs_product_licenses_keys SET license_status = 'expired' WHERE license_id IN([IN])";
3115 $sql = $this->prepare_in($sql, $ids);
3116
3117 $wpdb->query($sql);
3118
3119 }else if($_POST['baction'] == 'inactive'){
3120
3121 $ids = $_POST['post'];
3122
3123 $sql = "UPDATE {$wpdb->prefix}wc_fs_product_licenses_keys SET license_status = 'inactive' WHERE license_id IN([IN])";
3124 $sql = $this->prepare_in($sql, $ids);
3125
3126 $wpdb->query($sql);
3127
3128 }else if($_POST['baction'] == 'sold'){
3129
3130 $ids = $_POST['post'];
3131
3132 $sql = "UPDATE {$wpdb->prefix}wc_fs_product_licenses_keys SET license_status = 'sold' WHERE license_id IN([IN])";
3133 $sql = $this->prepare_in($sql, $ids);
3134
3135 $wpdb->query($sql);
3136
3137 }else if($_POST['baction'] == 'returned'){
3138
3139 $ids = $_POST['post'];
3140
3141 $sql = "UPDATE {$wpdb->prefix}wc_fs_product_licenses_keys SET license_status = 'returned' WHERE license_id IN([IN])";
3142 $sql = $this->prepare_in($sql, $ids);
3143
3144 $wpdb->query($sql);
3145
3146 }
3147
3148 $link = admin_url('admin.php?page=license-manager');
3149 wp_redirect($link);
3150
3151 die();
3152 }
3153
3154 /*****************/
3155 // Generator Bulk action Handler
3156 /*****************/
3157 function generator_bulk_action(){
3158 global $wpdb;
3159
3160 if($_POST['baction'] == 'trash'){
3161
3162 $ids = $_POST['post'];
3163
3164 $sql = "DELETE FROM {$wpdb->prefix}wc_fs_product_licenses_keys_generator_rules WHERE rule_id IN([IN])";
3165 $sql = $this->prepare_in($sql, $ids);
3166
3167 $wpdb->query($sql);
3168
3169 }else if($_POST['baction'] == 'activate'){
3170
3171 $ids = $_POST['post'];
3172
3173 $sql = "UPDATE {$wpdb->prefix}wc_fs_product_licenses_keys_generator_rules SET active = '1' WHERE rule_id IN([IN])";
3174 $sql = $this->prepare_in($sql, $ids);
3175
3176 $wpdb->query($sql);
3177
3178 }else if($_POST['baction'] == 'deactivate'){
3179
3180 $ids = $_POST['post'];
3181
3182 $sql = "UPDATE {$wpdb->prefix}wc_fs_product_licenses_keys_generator_rules SET active = '0' WHERE rule_id IN([IN])";
3183 $sql = $this->prepare_in($sql, $ids);
3184
3185 $wpdb->query($sql);
3186
3187 }
3188
3189 $link = admin_url('admin.php?page=license-manager');
3190 wp_redirect($link);
3191
3192 die();
3193 }
3194
3195
3196 /*****************/
3197 // Prepared statements with IN and NOT IN
3198 /*****************/
3199 public function prepare_in($sql, $vals){
3200 global $wpdb;
3201 $not_in_count = substr_count($sql, '[IN]');
3202 if($not_in_count > 0){
3203 $args = array(str_replace('[IN]', implode(', ', array_fill(0, count($vals), '%d')), str_replace('%', '%%', $sql)));
3204 // This will populate ALL the [IN]'s with the $vals, assuming you have more than one [IN] in the sql
3205 for($i=0; $i < substr_count($sql, '[IN]'); $i++){
3206 $args = array_merge($args, $vals);
3207 }
3208 $sql = call_user_func_array(array($wpdb, 'prepare'), array_merge($args));
3209 }
3210 return $sql;
3211 }
3212
3213 /*****************/
3214 // Generate license keys csv
3215 /*****************/
3216 public function generate_license_keys_csv($license_status = '', $product_id = ''){
3217 global $wpdb;
3218
3219 $args = '';
3220
3221 if($license_status != '' && $product_id != ''){
3222 $args .= "WHERE license_status = '{$license_status}' AND product_id = '{$product_id}'";
3223 }else if($license_status != ''){
3224 $args .= "WHERE license_status = '{$license_status}'";
3225 }else if($product_id != ''){
3226 $args .= "WHERE product_id = '{$product_id}'";
3227 }
3228
3229 $output = "sep=,\n";
3230
3231 $query = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}wc_fs_product_licenses_keys {$args} ORDER BY license_id DESC ", ARRAY_A);
3232
3233 if($query){
3234
3235 $output .= '"'.implode('","',array_keys($query[0])).'"'."\n";
3236
3237 foreach($query as $row){
3238 $output .= '"'.implode('","',$row).'"'."\n";
3239 }
3240 }
3241
3242
3243
3244 return $output;
3245 }
3246
3247 /*****************/
3248 // Generate generator rules csv
3249 /*****************/
3250 public function generate_generator_rules_csv($product_id = ''){
3251 global $wpdb;
3252
3253 $args = '';
3254
3255 if($product_id != ''){
3256 $args .= "WHERE product_id = '{$product_id}'";
3257 }
3258
3259 $output = "sep=,\n";
3260
3261 $query = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}wc_fs_product_licenses_keys_generator_rules {$args}", ARRAY_A);
3262
3263 if($query){
3264
3265 $output .= '"'.implode('","',array_keys($query[0])).'"'."\n";
3266
3267 foreach($query as $row){
3268 $output .= '"'.implode('","',$row).'"'."\n";
3269 }
3270 }
3271
3272
3273
3274 return $output;
3275 }
3276
3277 /*****************/
3278 // Generate Plugin Settings
3279 /*****************/
3280 public function generate_plugin_settings($product_id = ''){
3281 $output = '';
3282
3283 /////////////////////////
3284
3285
3286 $order_statuses = (array) $this->get_terms('shop_order_status', array('hide_empty' => 0, 'orderby' => 'id'));
3287
3288 if($order_statuses && !is_wp_error($order_statuses)) {
3289 foreach($order_statuses as $s) {
3290
3291 if(version_compare(WOOCOMMERCE_VERSION, '2.2', '>=' )) {
3292
3293 $s->slug = str_replace('wc-', '', $s->slug);
3294
3295 }
3296
3297 $output .= 'fslm_send_when_' . $s->slug . ' => ' . get_option('fslm_send_when_' . $s->slug). "\n";
3298 $output .= 'fslm_revoke_when_' . $s->slug . ' => ' . get_option('fslm_revoke_when_' . $s->slug). "\n";
3299 $output .= 'fslm_hide_when_' . $s->slug . ' => ' . get_option('fslm_hide_when_' . $s->slug). "\n";
3300
3301 }
3302 }
3303
3304
3305
3306 /////////////////////////
3307
3308 $output .= 'fslm_show_adminbar_notifs => ' . get_option('fslm_show_adminbar_notifs'). "\n";
3309 $output .= 'fslm_enable_cart_validation => ' . get_option('fslm_enable_cart_validation'). "\n";
3310 $output .= 'fslm_nb_rows_by_page => ' . get_option('fslm_nb_rows_by_page'). "\n";
3311 $output .= 'fslm_meta_key_name => ' . get_option('fslm_meta_key_name'). "\n";
3312 $output .= 'fslm_meta_key_name_plural => ' . get_option('fslm_meta_key_name_plural'). "\n";
3313 $output .= 'fslm_guest_customer => ' . get_option('fslm_guest_customer'). "\n";
3314
3315 $output .= 'fslm_generator_chars => ' . get_option('fslm_generator_chars'). "\n";
3316
3317 $output .= 'fslm_prefix => ' . get_option('fslm_prefix'). "\n";
3318 $output .= 'fslm_chunks_number => ' . get_option('fslm_chunks_number'). "\n";
3319 $output .= 'fslm_chunks_length => ' . get_option('fslm_chunks_length'). "\n";
3320 $output .= 'fslm_suffix => ' . get_option('fslm_suffix'). "\n";
3321 $output .= 'fslm_max_instance_number => ' . get_option('fslm_max_instance_number'). "\n";
3322 $output .= 'fslm_valid => ' . get_option('fslm_valid'). "\n";
3323 $output .= 'fslm_active => ' . get_option('fslm_active'). "\n";
3324
3325 $output .= 'fslm_notif_min_licenses_nb => ' . get_option('fslm_notif_min_licenses_nb'). "\n";
3326 $output .= 'fslm_notif_mail => ' . get_option('fslm_notif_mail'). "\n";
3327 $output .= 'fslm_notif_mail_to => ' . get_option('fslm_notif_mail_to'). "\n";
3328
3329 $output .= 'fslm_last_sent_notification_email_date => ' . get_option('fslm_last_sent_notification_email_date'). "\n";
3330 $output .= 'fslm_page_id => ' . get_option('fslm_page_id'). "\n";
3331
3332 $output .= 'fslm_mail_heading => ' . get_option('fslm_mail_heading'). "\n";
3333 $output .= 'fslm_mail_subject => ' . get_option('fslm_mail_subject'). "\n";
3334 $output .= 'fslm_mail_message => ' . str_replace(array("\r\n","\n\r","\n","\r"), "[NL]", get_option('fslm_mail_message')) . "\n";
3335
3336 $output .= 'fslm_encryption => ' . ENCRYPTION_KEY . '[SEP]' . ENCRYPTION_VI . "\n";
3337
3338
3339 $output .= 'fslm_delete_lk_db_tables => ' . get_option('fslm_delete_lk_db_tables'). "\n";
3340 $output .= 'fslm_delete_gr_db_tables => ' . get_option('fslm_delete_gr_db_tables'). "\n";
3341 $output .= 'fslm_delete_lp_db_tables => ' . get_option('fslm_delete_lp_db_tables'). "\n";
3342
3343 $output .= 'fslm_add_lk_wc_de => ' . get_option('fslm_add_lk_wc_de'). "\n";
3344 $output .= 'fslm_add_lk_se => ' . get_option('fslm_add_lk_se'). "\n";
3345 $output .= 'fslm_add_wc_header_and_footer => ' . get_option('fslm_add_wc_header_and_footer'). "\n";
3346
3347 return $output;
3348 }
3349
3350 /*****************/
3351 // Plugin Init
3352 /*****************/
3353 public function plugin_init(){
3354 load_plugin_textdomain('fslm', false, basename(dirname(__FILE__)). '/languages/');
3355 }
3356
3357 function plugin_deactivation_notices(){
3358 global $pagenow;
3359
3360 if(($pagenow == 'plugins.php') && ((get_option('fslm_delete_lp_db_tables', '')=='on') || (get_option('fslm_delete_lk_db_tables', '')=='on') || (get_option('fslm_delete_gr_db_tables', '')=='on'))){
3361 echo "<div class='updated'><p>" . __('Export your data before deactivating', 'fslm').' <strong>' . __('FS License Manager', 'fslm'). '</strong> <br>' . __('Database tables will be deleted, to deactivate without deleting the database table disable this option in <b>License Manager -> Settings -> Extra Settings</b>', 'fslm'). "</p></div>";
3362 }
3363 }
3364
3365 function newLine2br($str){
3366 $newLineArray = array("\r\n","\n\r","\n","\r");
3367 $output = str_replace($newLineArray,"<br>",$str);
3368
3369 return $output;
3370 }
3371
3372 function br2newLine($str){
3373 $newLineArray = array("<br>","<br />","<br/>");
3374 $output = str_replace($newLineArray,"\n\r",$str);
3375
3376 return $output;
3377 }
3378
3379 function set_encryption_key($key, $vi, $action = 'set') {
3380 $upload_directory = wp_upload_dir();
3381 $target_dir = $upload_directory['basedir'] . '/fslm_files/';
3382
3383 if (!file_exists($target_dir)) {
3384 wp_mkdir_p($target_dir);
3385
3386 $fp = fopen($target_dir . '.htaccess', 'w');
3387 fwrite($fp, 'deny from all');
3388 fclose($fp);
3389
3390 $fp = fopen($target_dir . 'encryption_key.php', 'w');
3391 fwrite($fp, "<?php define(\"ENCRYPTION_KEY\", \"" . $key . "\");\ndefine(\"ENCRYPTION_VI\", \"" . $vi . "\");");
3392 fclose($fp);
3393
3394 $fp = fopen($target_dir . 'index.php', 'w');
3395 fwrite($fp, '<?php');
3396 fclose($fp);
3397 }else if ($action = 'update'){
3398 $fp = fopen($target_dir . 'encryption_key.php', 'w');
3399 fwrite($fp, "<?php define(\"ENCRYPTION_KEY\", \"" . $key . "\");\ndefine(\"ENCRYPTION_VI\", \"" . $vi . "\");");
3400 fclose($fp);
3401 }
3402 }
3403
3404 function encrypt_decrypt($action, $string, $secret_key, $secret_iv) {
3405 $output = false;
3406
3407 if ($secret_key == "" && $secret_iv == "") {
3408 return $string;
3409 }
3410
3411 if (!extension_loaded('openssl')) {
3412 return $string;
3413 }
3414
3415 $encrypt_method = "AES-256-CBC";
3416
3417 // hash
3418 $key = hash('sha256', $secret_key);
3419
3420 // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
3421 $iv = substr(hash('sha256', $secret_iv), 0, 16);
3422
3423 if($action == 'encrypt') {
3424 $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
3425 $output = base64_encode($output);
3426 } else if($action == 'decrypt'){
3427 $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
3428 }
3429
3430 return $output;
3431 }
3432
3433 function apply_mail_text_filters($text, $order_id){
3434
3435 if('' == trim($text))
3436 return $text;
3437
3438 $meta = get_post_custom($order_id, true);
3439
3440 $sitename = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
3441
3442 $siteurl = wp_specialchars_decode(get_option('home'), ENT_QUOTES);
3443
3444 if(false !== strpos($text, '[order_id]')){
3445 $text = str_replace('[order_id]', $order_id, $text);
3446
3447 }
3448
3449 if(false !== strpos($text, '[bfname]')){
3450
3451 $fname = $meta['_billing_first_name'][0];
3452
3453 if(!$fname || empty($fname))
3454 $text = str_replace('[bfname]', '', $text);
3455 else
3456 $text = str_replace('[bfname]', $fname, $text);
3457 }
3458
3459 if(false !== strpos($text, '[blname]')){
3460
3461 $lname = $meta['_billing_last_name'][0];
3462
3463 if(!$lname || empty($lname))
3464 $text = str_replace('[blname]', '', $text);
3465 else
3466 $text = str_replace('[blname]', $lname, $text);
3467 }
3468
3469 if(false !== strpos($text, '[sfname]')){
3470
3471 $fname = $meta['_shipping_first_name'][0];
3472
3473 if(!$fname || empty($fname))
3474 $text = str_replace('[sfname]', '', $text);
3475 else
3476 $text = str_replace('[sfname]', $fname, $text);
3477 }
3478
3479 if(false !== strpos($text, '[slname]')){
3480
3481 $lname = $meta['_shipping_last_name'][0];
3482
3483 if(!$lname || empty($lname))
3484 $text = str_replace('[slname]', '', $text);
3485 else
3486 $text = str_replace('[slname]', $lname, $text);
3487 }
3488
3489 if(false !== strpos($text, '[site_name]'))
3490 $text = str_replace('[site_name]', $sitename, $text);
3491
3492 if(false !== strpos($text, '[url]'))
3493 $text = str_replace('[url]', $siteurl, $text);
3494
3495 if(false !== strpos($text, '[myaccount_url]')){
3496 $ma_id = woocommerce_get_page_id('myaccount');
3497 $ma_url = get_permalink($ma_id);
3498 $text = str_replace('[myaccount_url]', $ma_url, $text);
3499 }
3500
3501 return $text;
3502 }
3503
3504 function add_actions(){
3505 $on_status = array('completed');
3506
3507 $on_status_send = array('completed');
3508 $on_status_revoke = array('refunded');
3509 $on_status_hide = array();
3510
3511
3512 /////////////////////////
3513
3514
3515 $order_statuses = (array) $this->get_terms('shop_order_status', array('hide_empty' => 0, 'orderby' => 'id'));
3516
3517 if($order_statuses && !is_wp_error($order_statuses)) {
3518 foreach($order_statuses as $s) {
3519
3520 if(version_compare(WOOCOMMERCE_VERSION, '2.2', '>=' )) {
3521
3522 $s->slug = str_replace('wc-', '', $s->slug);
3523
3524 }
3525
3526 $default_send = 'off';
3527 $default_revoke = 'off';
3528 $default_hide = 'off';
3529
3530 if (in_array($s->slug, $on_status_send)) $default_send = 'on';
3531 if (in_array($s->slug, $on_status_revoke)) $default_revoke = 'on';
3532 if (in_array($s->slug, $on_status_hide)) $default_hide = 'on';
3533
3534 if(get_option('fslm_send_when_' . $s->slug, $on_status_send)== 'on'){
3535 add_action('woocommerce_order_status_' . $s->slug, array($this, 'fslm_send_license_keys'), 1, 1);
3536 }
3537
3538 if(get_option('fslm_revoke_when_' . $s->slug, $on_status_revoke)== 'on'){
3539 add_action('woocommerce_order_status_' . $s->slug, array($this, 'fslm_revoke_license_keys'), 1, 1);
3540 }
3541
3542 if(get_option('fslm_hide_when_' . $s->slug, $on_status_hide)== 'on'){
3543 add_action('woocommerce_order_status_' . $s->slug, array($this, 'fslm_hide_license_keys'), 1, 1);
3544 }
3545
3546 }
3547 }
3548
3549
3550 /////////////////////////
3551
3552 }
3553
3554
3555 public static function get_terms($taxo = 'shop_order_status', $args = array()) {
3556
3557 if(version_compare(WOOCOMMERCE_VERSION, '2.2', '<')) {
3558
3559 return get_terms( $taxo, $args );
3560
3561 } else if(version_compare(WOOCOMMERCE_VERSION, '2.2', '>=')) {
3562
3563 $s = wc_get_order_statuses();
3564
3565 if(!empty($s)) {
3566
3567 $i = 1;
3568
3569 foreach($s as $key => $val) {
3570
3571 if(empty($key) || empty($val))
3572 continue;
3573
3574 $status = new stdClass();
3575
3576 $status->term_id = $i;
3577
3578 $status->slug = $key;
3579
3580 $status->name = $val;
3581
3582 $statuses[$i] = $status;
3583
3584 $i++;
3585
3586 }
3587
3588 return $statuses;
3589 }
3590
3591 }
3592 }
3593
3594
3595 public function license($code, $eu) {
3596
3597 $result = false;
3598 $our_item_id = base64_decode('MTY2MzY3NDg=');
3599 $u = base64_decode('ZmlyYXNzYWlkaQ==');
3600 $api_key = 'bzw0kaf902owwjowkqwsz5ks0ihc39ti';
3601 $url = base64_decode('aHR0cDovL21hcmtldHBsYWNlLmVudmF0by5jb20vYXBpL2VkZ2Uv') . "$u/$api_key/" . base64_decode('dmVyaWZ5LXB1cmNoYXNl') . ":$code.json";
3602 $ch = curl_init($url);
3603
3604 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
3605 curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
3606 $json_res = curl_exec($ch);
3607 $data = json_decode($json_res, true);
3608 $purchases = $data['verify-purchase'];
3609 curl_close($ch);
3610
3611
3612 if(isset($purchases['buyer'])){
3613
3614 // format single purchases same as multi purchases
3615 $purchases = array($purchases);
3616
3617 }
3618
3619 $purchase_details = array();
3620 foreach($purchases as $purchase){
3621
3622 $purchase = (array)$purchase; // json issues
3623 if(((int)$purchase['item_id'] == (int)$our_item_id) && ($purchase['buyer'] == $eu)) {
3624
3625 // we have a winner!
3626 $result = true;
3627 $purchase_details = $purchase;
3628
3629 }
3630
3631 }
3632
3633 // TODO: set final url after seting up the VPS
3634 $aurl = 'https://store.firassaidi.com/wp-admin/admin-ajax.php';
3635 $fields = array(
3636 "action" => urlencode('fslm_activation'),
3637 "item_id" => urlencode($result?$purchase_details['item_id']:''),
3638 "purchase_code" => urlencode($code),
3639 "buyer" => urlencode($eu),
3640 "buyer_ip" => urlencode($this->get_ip()),
3641 "domain_name" => urlencode($_SERVER['SERVER_NAME']),
3642 "item_name" => urlencode($result?$purchase_details['item_name']:''),
3643 "license" => urlencode($result?$purchase_details['licence']:''),
3644 "purchase_date" => urlencode($result?$purchase_details['created_at']:''),
3645 "supported_until" => urlencode($result?$purchase_details['supported_until']:''),
3646 "status" => urlencode($result?'active':'inactive'),
3647 "last_validation" => urlencode(date("Y-m-d H:i:s")),
3648 "ajax_url" => urlencode(admin_url('admin-ajax.php'))
3649 );
3650
3651 //url-ify the data for the POST
3652 foreach($fields as $key=>$value) {
3653
3654 $fields_string .= $key.'='.$value.'&';
3655
3656 }
3657
3658 rtrim($fields_string, '&');
3659
3660 //open connection
3661 $ch = curl_init();
3662
3663 //set the url, number of POST vars, POST data
3664 curl_setopt($ch, CURLOPT_URL, $aurl);
3665 curl_setopt($ch, CURLOPT_POST, count($fields));
3666 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
3667 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
3668 curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
3669 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
3670
3671 //execute post
3672 $aresult = curl_exec($ch);
3673
3674 //echo('<pre>');
3675 //print_r(curl_getinfo($ch));die();
3676
3677
3678 //close connection
3679 curl_close($ch);
3680
3681 // do something with the users purchase details,
3682 // eg: check which license they've bought, save their username something
3683 if($result){
3684
3685 $status = update_option('fslm_status', 'active');
3686 $buyer = update_option('fslm_buyer', $purchase_details['buyer']);
3687 $created_at = update_option('fslm_created_at', $purchase_details['created_at']);
3688 $licence = update_option('fslm_licence', $purchase_details['licence']);
3689 $item_name = update_option('fslm_item_name', $purchase_details['item_name']);
3690 $item_id = update_option('fslm_item_id', $purchase_details['item_id']);
3691 $supported_until = update_option('fslm_supported_until', $purchase_details['supported_until']);
3692 $pc = update_option('fslm_pc', $code);
3693
3694 return($purchase_details);
3695
3696 }
3697
3698
3699 return(false);
3700
3701 }
3702
3703 public function rv_license($code, $eu) {
3704
3705 $result = false;
3706 $our_item_id = base64_decode('MTY2MzY3NDg=');
3707 $u = base64_decode('ZmlyYXNzYWlkaQ==');
3708 $api_key = 'bzw0kaf902owwjowkqwsz5ks0ihc39ti';
3709 $url = base64_decode('aHR0cDovL21hcmtldHBsYWNlLmVudmF0by5jb20vYXBpL2VkZ2Uv') . "$u/$api_key/" . base64_decode('dmVyaWZ5LXB1cmNoYXNl') . ":$code.json";
3710 $ch = curl_init($url);
3711
3712 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
3713 curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
3714 $json_res = curl_exec($ch);
3715 $data = json_decode($json_res, true);
3716 $purchases = $data['verify-purchase'];
3717 curl_close($ch);
3718
3719
3720 if(isset($purchases['buyer'])){
3721
3722 // format single purchases same as multi purchases
3723 $purchases = array($purchases);
3724
3725 }
3726
3727 $purchase_details = array();
3728 foreach($purchases as $purchase){
3729
3730 $purchase = (array)$purchase; // json issues
3731 if(((int)$purchase['item_id'] == (int)$our_item_id) && ($purchase['buyer'] == $eu)) {
3732
3733 // we have a winner!
3734 $result = true;
3735 $purchase_details = $purchase;
3736
3737 }
3738
3739 }
3740
3741 $status = get_option('fslm_status', 'N/A');
3742
3743 // TODO: set final url after seting up the VPS
3744 $aurl = 'https://store.firassaidi.com/wp-admin/admin-ajax.php';
3745 $fields = array(
3746 "action" => urlencode('fslm_activation'),
3747 "item_id" => urlencode($result?$purchase_details['item_id']:''),
3748 "purchase_code" => urlencode($code),
3749 "buyer" => urlencode($eu),
3750 "buyer_ip" => urlencode($this->get_ip()),
3751 "domain_name" => urlencode($_SERVER['SERVER_NAME']),
3752 "item_name" => urlencode($result?$purchase_details['item_name']:''),
3753 "license" => urlencode($result?$purchase_details['licence']:''),
3754 "purchase_date" => urlencode($result?$purchase_details['created_at']:''),
3755 "supported_until" => urlencode($result?$purchase_details['supported_until']:''),
3756 "status" => urlencode($status),
3757 "last_validation" => urlencode(date("Y-m-d H:i:s")),
3758 "ajax_url" => urlencode(admin_url('admin-ajax.php'))
3759 );
3760
3761
3762
3763 //url-ify the data for the POST
3764 foreach($fields as $key=>$value) {
3765
3766 $fields_string .= $key.'='.$value.'&';
3767
3768 }
3769
3770 rtrim($fields_string, '&');
3771
3772 //open connection
3773 $ch = curl_init();
3774
3775 //set the url, number of POST vars, POST data
3776 curl_setopt($ch, CURLOPT_URL, $aurl);
3777 curl_setopt($ch, CURLOPT_POST, count($fields));
3778 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
3779 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
3780 curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
3781 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
3782
3783 //execute post
3784 $aresult = curl_exec($ch);
3785
3786 //echo('<pre>');
3787 //print_r(curl_getinfo($ch));die();
3788
3789 header("Access-Control-Allow-Origin: *");
3790 //close connection
3791 curl_close($ch);
3792
3793 // do something with the users purchase details,
3794 // eg: check which license they've bought, save their username something
3795 if($result){
3796
3797 return ($purchase_details);
3798
3799 }
3800
3801 return(false);
3802
3803 }
3804
3805 function get_ip() {
3806
3807 if(!empty($_SERVER['HTTP_CLIENT_IP'])) {
3808
3809 return $_SERVER['HTTP_CLIENT_IP'];
3810
3811 }elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3812
3813 return $_SERVER['HTTP_X_FORWARDED_FOR'];
3814
3815 }else {
3816
3817 return $_SERVER['REMOTE_ADDR'];
3818
3819 }
3820
3821 }
3822
3823 public function privapi_requests_handler(){
3824
3825 if(isset($_GET['fslmprivapirequest'])){
3826
3827
3828 if(($_GET['fslmprivapirequest'] == 'verification')){
3829
3830 $output = $this->get_license_details();
3831
3832 echo $output;
3833
3834 die();
3835
3836 }
3837
3838 }
3839
3840 }
3841
3842 public function is_pc_valid($pc) {
3843
3844 if(preg_match("/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/", $pc)) {
3845
3846 return(true);
3847
3848 }
3849
3850 return(false);
3851
3852 }
3853
3854 public function get_license_details() {
3855
3856 $status = get_option('fslm_status', 'N/A');
3857 $buyer = get_option('fslm_buyer', 'N/A');
3858 $created_at = get_option('fslm_created_at', 'N/A');
3859 $licence = get_option('fslm_licence', 'N/A');
3860 $item_name = get_option('fslm_item_name', 'N/A');
3861 $item_id = get_option('fslm_item_id', 'N/A');
3862 $supported_until = get_option('fslm_supported_until', 'N/A');
3863 $pc = get_option('fslm_pc', 'N/A');
3864
3865 $output = '<pre>';
3866 $output .= 'License Verification:' . "\n" . "\n";
3867 $output .= "Status: " . $status . "\n";
3868 $output .= "Buyer: " . $buyer . "\n";
3869 $output .= "Created At: " . $created_at . "\n";
3870 $output .= "License: " . $licence . "\n";
3871 $output .= "Item Name: " . $item_name . "\n";
3872 $output .= "Item ID: " . $item_id . "\n";
3873 $output .= "Supported Until: " . $supported_until . "\n";
3874 $output .= "Purchase Code: " . $pc . "\n";
3875 $output .= '</pre>';
3876
3877 return($output);
3878
3879 }
3880
3881 public static function is_active() {
3882 return true;
3883 if(get_option('fslm_status', 'N/A') == 'active') {
3884 return true;
3885 }
3886
3887 return false;
3888
3889 }
3890
3891
3892
3893}
3894
3895
3896// Plugin Settings Page
3897
3898class FSLM_Settings {
3899
3900 /*****************/
3901 // Start up
3902 /*****************/
3903 public function __construct(){
3904
3905 add_action('admin_enqueue_scripts', array($this, 'load_license_manager_admin_scripts'));
3906 add_action('admin_menu', array($this, 'add_plugin_menu_and_pages'));
3907 if(FS_WC_licenses_Manager::is_active()) {
3908 add_action('admin_init', array($this, 'page_init'));
3909 }
3910
3911 }
3912
3913 /*****************/
3914 // Plugin Menu
3915 /*****************/
3916 public function add_plugin_menu_and_pages(){
3917
3918 if(FS_WC_licenses_Manager::is_active()) {
3919
3920 add_menu_page(__('License Manager', 'fslm'), __('License Manager', 'fslm'), 'manage_woocommerce', 'license-manager', array($this, 'admin_page_callback'), 'dashicons-lock', 55.5);
3921 add_submenu_page('license-manager', __('License Key Generator', 'fslm'), __('License Key Generator', 'fslm'), 'manage_woocommerce', 'license-manager-license-key-generator', array($this, 'license_key_generator_page_callback'));
3922 add_submenu_page('license-manager', __('Add License Key', 'fslm'), __('Add License Key', 'fslm'), 'manage_woocommerce', 'license-manager-add-license-key', array($this, 'add_license_key_page_callback'));
3923 add_submenu_page('license-manager', __('Add Generator Rule', 'fslm'), __('Add Generator Rule', 'fslm'), 'manage_woocommerce', 'license-manager-license-generator', array($this, 'add_license_key_generator_rule_page_callback'));
3924 add_submenu_page('license-manager', __('Settings', 'fslm'), __('Settings', 'fslm'), 'manage_woocommerce', 'license-manager-settings', array($this, 'settings_page_callback'));
3925 add_submenu_page('license-manager', __('Import', 'fslm'), __('Import', 'fslm'), 'manage_woocommerce', 'license-manager-import', array($this, 'import_page_callback'));
3926 add_submenu_page('license-manager', __('Export', 'fslm'), __('Export', 'fslm'), 'manage_woocommerce', 'license-manager-export', array($this, 'export_page_callback'));
3927 add_submenu_page('license-manager', __('About', 'fslm'), __('About', 'fslm'), 'manage_woocommerce', 'license-manager-about', array($this, 'about_page_callback'));
3928
3929 add_submenu_page(
3930 null,
3931 __('Welcome' ,'fslm'),
3932 __('Welcome' ,'fslm'),
3933 'manage_woocommerce',
3934 'license-manager-welcome',
3935 array($this, 'welcome_page')
3936 );
3937
3938 }else {
3939
3940 add_menu_page(__('License Manager', 'fslm'), __('License Manager', 'fslm'), 'manage_woocommerce', 'license-manager-welcome', array($this, 'welcome_page'), 'dashicons-lock', 55.5);
3941
3942 }
3943
3944 }
3945
3946 public function welcome_page(){
3947 require("includes/welcome_page.php");
3948 }
3949
3950 /*****************/
3951 // Plugin Menu: Admin Page
3952 /*****************/
3953 public function admin_page_callback(){
3954 require("includes/license_manager.php");
3955 }
3956
3957 /*****************/
3958 // Plugin Menu: Admin Page
3959 /*****************/
3960 public function about_page_callback(){
3961 require("includes/about.php");
3962 }
3963
3964 /*****************/
3965 // Plugin Menu: Add License Key
3966 /*****************/
3967 public function add_license_key_page_callback(){
3968 require("includes/add_license_key.php");
3969 }
3970
3971 /*****************/
3972 // Plugin Menu: License Key Generator
3973 /*****************/
3974 public function license_key_generator_page_callback(){
3975 require("includes/license_key_generator.php");
3976 }
3977
3978 /*****************/
3979 // Plugin Menu: Add License Key Generator Rule
3980 /*****************/
3981 public function add_license_key_generator_rule_page_callback(){
3982 require("includes/add_generator_rule.php");
3983 }
3984
3985 /*****************/
3986 // Plugin Menu: Settings Page
3987 /*****************/
3988 public function settings_page_callback(){
3989 require("includes/settings_page.php");
3990 }
3991
3992 /*****************/
3993 // Plugin Menu: Import Page
3994 /*****************/
3995 public function import_page_callback(){
3996 require("includes/lm_import.php");
3997 }
3998
3999 /*****************/
4000 // Plugin Menu: Export Page
4001 /*****************/
4002 public function export_page_callback(){
4003 require("includes/lm_export.php");
4004 }
4005
4006 /*****************/
4007 // Register Settings
4008 /*****************/
4009 public function page_init(){
4010
4011 /////////////////////////
4012
4013
4014 $order_statuses = (array) FS_WC_licenses_Manager::get_terms('shop_order_status', array('hide_empty' => 0, 'orderby' => 'id'));
4015
4016 if($order_statuses && !is_wp_error($order_statuses)) {
4017 foreach($order_statuses as $s) {
4018
4019 if(version_compare(WOOCOMMERCE_VERSION, '2.2', '>=' )) {
4020
4021 $s->slug = str_replace('wc-', '', $s->slug);
4022
4023 }
4024
4025 register_setting('fslm_order_status_option_group', 'fslm_send_when_' . $s->slug);
4026 register_setting('fslm_order_status_option_group', 'fslm_revoke_when_' . $s->slug);
4027 register_setting('fslm_order_status_option_group', 'fslm_hide_when_' . $s->slug);
4028
4029 }
4030 }
4031
4032
4033
4034 /////////////////////////
4035
4036 register_setting('fslm_email_template_option_group', 'fslm_mail_heading');
4037 register_setting('fslm_email_template_option_group', 'fslm_mail_subject');
4038 register_setting('fslm_email_template_option_group', 'fslm_mail_message');
4039 register_setting('fslm_email_template_option_group', 'fslm_add_wc_header_and_footer');
4040 register_setting('fslm_email_template_option_group', 'fslm_add_lk_wc_de');
4041 register_setting('fslm_email_template_option_group', 'fslm_add_lk_se');
4042
4043 register_setting('fslm_general_option_group', 'fslm_show_adminbar_notifs');
4044 register_setting('fslm_general_option_group', 'fslm_guest_customer');
4045 register_setting('fslm_general_option_group', 'fslm_enable_cart_validation');
4046 register_setting('fslm_general_option_group', 'fslm_nb_rows_by_page');
4047 register_setting('fslm_general_option_group', 'fslm_meta_key_name');
4048 register_setting('fslm_general_option_group', 'fslm_generator_chars');
4049
4050 register_setting('fslm_general_option_group', 'fslm_meta_key_name_plural');
4051
4052 register_setting('fslm_lkg_option_group', 'fslm_prefix');
4053 register_setting('fslm_lkg_option_group', 'fslm_chunks_number');
4054 register_setting('fslm_lkg_option_group', 'fslm_chunks_length');
4055 register_setting('fslm_lkg_option_group', 'fslm_suffix');
4056 register_setting('fslm_lkg_option_group', 'fslm_max_instance_number');
4057 register_setting('fslm_lkg_option_group', 'fslm_valid');
4058 register_setting('fslm_lkg_option_group', 'fslm_active');
4059
4060 register_setting('fslm_notifications_option_group', 'fslm_notif_min_licenses_nb');
4061 register_setting('fslm_notifications_option_group', 'fslm_notif_mail');
4062 register_setting('fslm_notifications_option_group', 'fslm_notif_mail_to');
4063
4064 register_setting('fslm_hidden_options', 'fslm_last_sent_notification_email_date');
4065 register_setting('fslm_hidden_options', 'fslm_page_id');
4066
4067 register_setting('fslm_extra_option_group', 'fslm_delete_lp_db_tables');
4068 register_setting('fslm_extra_option_group', 'fslm_delete_lk_db_tables');
4069 register_setting('fslm_extra_option_group', 'fslm_delete_gr_db_tables');
4070
4071 }
4072
4073 /*****************/
4074 // Load required scripts
4075 /*****************/
4076 function load_license_manager_admin_scripts(){
4077
4078 wp_enqueue_style('fslm_License_Manager_Style', plugins_url('/assets/css/style.css', __FILE__), array(), '2205');
4079 wp_enqueue_style('fslm_select2', plugins_url('/assets/select2/css/select2.min.css', __FILE__), array(), '2205');
4080
4081 if(isset($_GET['tab']) && $_GET['tab'] == 'email_template') { // too aboid conflict with other plugins that use TinyMCE
4082 wp_enqueue_script('fslm_tinymce', plugins_url('/assets/js/tinymce/tinymce.min.js', __FILE__), array('jquery'));
4083 }
4084
4085 wp_enqueue_script('fslm_json_ui', plugins_url('/assets/js/jsoneditor.min.js', __FILE__), array('jquery'));
4086 wp_enqueue_script('fslm_SortTable', plugins_url('/assets/js/sortTable.js', __FILE__), array('jquery'));
4087 wp_enqueue_script('fslm_select2_js', plugins_url('/assets/select2/js/select2.full.min.js', __FILE__), array('jquery'));
4088 wp_enqueue_script('fslm_Main', plugins_url('/assets/js/main.js', __FILE__), array('jquery'), '6');
4089
4090 }
4091
4092}
4093
4094
4095
4096if(in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))){
4097 $fs_wc_licenses_manager = new FS_WC_licenses_Manager();
4098}
4099
4100if(in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))){
4101 if(is_admin()){
4102 $fslm_settings = new FSLM_Settings();
4103 }
4104}