-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdf-forms-for-woocommerce.php
2949 lines (2514 loc) · 100 KB
/
pdf-forms-for-woocommerce.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: PDF Forms Filler for WooCommerce
* Plugin URI: https://pdfformsfiller.org/
* Description: Automatically fill PDF forms with WooCommerce orders and attach generated PDFs to email notifications and order downloads.
* Version: 1.1.0
* Requires at least: 5.4
* Requires PHP: 5.5
* Requires Plugins: woocommerce
* WC requires at least: 7.1.0
* WC tested up to: 9.5
* Author: Maximum.Software
* Author URI: https://maximum.software/
* Text Domain: pdf-forms-for-woocommerce
* Domain Path: /languages
* License: GPLv3
* License URI: https://www.gnu.org/licenses/gpl-3.0.html
*/
if( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
require_once untrailingslashit( dirname( __FILE__ ) ) . '/src/tgm-config.php';
require_once untrailingslashit( dirname( __FILE__ ) ) . '/src/wrapper.php';
if( ! class_exists( 'Pdf_Forms_For_WooCommerce', false ) )
{
class Pdf_Forms_For_WooCommerce
{
const VERSION = '1.1.0';
const MIN_WC_VERSION = '7.1.0';
const MAX_WC_VERSION = '9.5.99';
private static $BLACKLISTED_WC_VERSIONS = array();
const META_KEY = '_pdf-forms-for-woocommerce-data';
private static $instance = null;
private $pdf_ninja_service = null;
private $service = null;
private $registered_services = false;
private $tmp_storage = null;
private $filled_pdfs = array();
private $new_orders = array();
private $delayed_saving_orders = array();
private $do_not_save_orders = array();
private function __construct()
{
add_action( 'admin_notices', array( $this, 'admin_notices' ) );
add_action( 'plugins_loaded', array( $this, 'plugin_init' ) );
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'action_links' ) );
}
/**
* Returns a global instance of this class
*/
public static function get_instance()
{
if( ! self::$instance )
self::$instance = new self;
return self::$instance;
}
/**
* Runs after all plugins have been loaded
*/
public function plugin_init()
{
add_action( 'init', array( $this, 'load_textdomain' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
if( ! class_exists( 'WooCommerce' ) || ! defined( 'WC_VERSION' ) )
return;
add_action( 'wp_ajax_pdf_forms_for_woocommerce_get_attachment_data', array( $this, 'wp_ajax_get_attachment_data' ) );
add_action( 'wp_ajax_pdf_forms_for_woocommerce_query_page_image', array( $this, 'wp_ajax_query_page_image' ) );
add_action( 'wp_ajax_pdf_forms_for_woocommerce_generate_pdf_ninja_key', array( $this, 'wp_ajax_generate_pdf_ninja_key') );
add_action( 'wp_ajax_pdf_forms_for_woocommerce_clear_messages', array( $this, 'wp_ajax_clear_messages') );
add_action( 'wp_ajax_pdf_forms_for_woocommerce_reset_order_settings', array( $this, 'wp_ajax_reset_order_settings') );
add_action( 'wp_ajax_pdf_forms_for_woocommerce_reset_order_pdfs', array( $this, 'wp_ajax_reset_order_pdfs') );
add_action( 'init', array( $this, 'register_meta' ) );
add_action( 'admin_menu', array( $this, 'register_services' ) );
add_action( 'add_meta_boxes', array( $this, 'register_order_metabox' ) );
add_action( 'before_woocommerce_init', array( $this, 'before_woocommerce_init' ) );
add_action( 'woocommerce_new_order', array( $this, 'woocommerce_new_order' ), 10, 2 ); // since 2.7.0
add_filter( 'woocommerce_before_order_object_save', array( $this, 'woocommerce_before_order_object_save' ), 10, 2 );
add_filter( 'woocommerce_after_order_object_save', array( $this, 'woocommerce_after_order_object_save' ), 10, 2 );
add_filter( 'woocommerce_email_attachments', array( $this, 'attach_pdfs' ), 10, 4 );
add_action( 'woocommerce_email_sent', array( $this, 'remove_tmp_storage' ), 99, 0 ); // since WC 5.6.0
add_filter( 'woocommerce_get_item_downloads', array( $this, 'woocommerce_get_item_downloads' ), 10, 3 );
add_filter( 'woocommerce_customer_available_downloads', array( $this, 'woocommerce_customer_available_downloads' ), 10, 2 );
add_action( 'before_delete_post', array( $this, 'before_delete_post' ), 10, 1 );
add_action( 'woocommerce_before_delete_order', array( $this, 'woocommerce_before_delete_order' ), 10, 1 ); // since WC 7.1.0
add_action( 'woocommerce_before_delete_order_item', array( $this, 'woocommerce_before_delete_order_item' ), 10, 1 ); // since WC 2.0.9
add_filter( 'woocommerce_product_data_tabs', array( $this, 'add_product_data_tab' ) );
add_action( 'woocommerce_product_data_panels', array( $this, 'print_product_data_tab_contents' ) );
add_action( 'woocommerce_process_product_meta', array( $this, 'save_product_data' ), 99 );
add_filter( 'woocommerce_get_settings_pages', array( $this, 'register_settings' ) );
if( $service = $this->get_service() )
{
$service->plugin_init();
if( $service != $this->pdf_ninja_service )
$this->pdf_ninja_service->plugin_init();
}
}
/*
* Loads plugin textdomain
*/
public function load_textdomain()
{
load_plugin_textdomain( 'pdf-forms-for-woocommerce', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
/*
* Declares WC compatibility
*/
public function before_woocommerce_init()
{
if( is_callable( array( '\Automattic\WooCommerce\Utilities\FeaturesUtil', 'declare_compatibility' ) ) )
\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
}
/*
* Checks if WC High-Performance Order Storage is enabled
*/
public static function is_wc_hpos_enabled()
{
return
is_callable( array( '\Automattic\WooCommerce\Utilities\OrderUtil', 'custom_orders_table_usage_is_enabled' ) )
&& \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled();
}
/*
* Registers the meta key for settings
*/
public function register_meta()
{
register_meta( 'post', self::META_KEY, array(
'show_in_rest' => false,
'single' => true,
'type' => 'string',
'auth_callback' => '__return_false',
) );
}
/**
* Adds a metabox to edit order page
*/
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- This function does not need nonce verification because it doesn't process any data, it only adds a meta box
public function register_order_metabox()
{
// get current order
$order = wc_get_order();
if( ! is_a( $order, 'WC_Order' ) )
return;
// don't display meta box if the order doesn't have attachments and its item products don't have attachments
$order_has_attachments = false;
$order_item_product_has_attachments = false;
// check order metadata for attachments
$settings = $this->get_order_metadata( $order );
if( is_array( $settings )
&& isset( $settings['product-settings'] )
&& is_array( $product_settings = $settings['product-settings'] ) )
{
foreach( $product_settings as $settings )
{
if( is_array( $settings )
&& isset( $settings['attachments'] )
&& is_array( $attachments = $settings['attachments'] )
&& ! empty( $attachments ) )
{
$order_has_attachments = true;
break;
}
}
}
if( ! $order_has_attachments )
{
// check order items for attachments
$items = $order->get_items();
foreach( $items as $item )
{
$product = $item->get_product();
if( is_a( $product, 'WC_Product' ) )
{
$settings = self::get_metadata( $product->get_id(), 'product-settings' );
if( is_array( $settings )
&& isset( $settings['attachments'] )
&& is_array( $attachments = $settings['attachments'] )
&& ! empty( $attachments ) )
{
$order_item_product_has_attachments = true;
break;
}
}
}
}
if( ! $order_has_attachments && ! $order_item_product_has_attachments )
return;
add_meta_box(
'pdf-forms-for-woocommerce-metabox', // ID
__( 'PDF Forms Filler', 'pdf-forms-for-woocommerce' ), // title
array( $this, 'display_order_metabox' ), // callback
self::is_wc_hpos_enabled() ? wc_get_page_screen_id( 'shop-order' ) : 'shop_order',
'side', // context
'default' // priority
);
}
// phpcs:enable WordPress.Security.NonceVerification.Recommended
/**
* Add PDF Forms settings page to WooCommerce settings
*/
public function register_settings( $settings )
{
require_once untrailingslashit( dirname( __FILE__ ) ) . '/src/integration/wc-settings-page.php';
$settings[] = Pdf_Forms_For_WooCommerce_Settings_Page::get_instance();
if( $service = $this->get_service() )
{
$service->register_settings();
if( $service != $this->pdf_ninja_service )
$this->pdf_ninja_service->register_settings();
}
return $settings;
}
/**
* Adds plugin action links
*/
public function action_links( $links )
{
$links[] = '<a target="_blank" href="https://wordpress.org/support/plugin/pdf-forms-for-woocommerce/">'.esc_html__( "Support", 'pdf-forms-for-woocommerce' ).'</a>';
return $links;
}
/**
* Prints admin notices
*/
public function admin_notices()
{
if( ! class_exists( 'WooCommerce' ) || ! defined( 'WC_VERSION' ) )
{
if( current_user_can( 'activate_plugins' ) )
echo Pdf_Forms_For_WooCommerce::render_error_notice( 'woocommerce-not-installed', array(
'label' => esc_html__( "PDF Forms Filler for WooCommerce Error", 'pdf-forms-for-woocommerce' ),
'message' => esc_html__( "The required plugin 'WooCommerce' version is not installed!", 'pdf-forms-for-woocommerce' ),
) );
return;
}
if( ! $this->is_wc_version_supported( WC_VERSION ) )
if( current_user_can( 'activate_plugins' ) )
echo Pdf_Forms_For_WooCommerce::render_warning_notice( 'unsupported-woocommerce-version-'.WC_VERSION, array(
'label' => esc_html__( "PDF Forms Filler for WooCommerce Warning", 'pdf-forms-for-woocommerce' ),
'message' =>
self::replace_tags(
esc_html__( "The currently installed version of 'WooCommerce' plugin ({current-woocommerce-version}) may not be supported by the current version of 'PDF Forms Filler for WooCommerce' plugin ({current-plugin-version}), please switch to 'WooCommerce' plugin version {supported-woocommerce-version} or below to ensure that 'PDF Forms Filler for WooCommerce' plugin would work correctly.", 'pdf-forms-for-woocommerce' ),
array(
'current-woocommerce-version' => esc_html( defined( 'WC_VERSION' ) ? WC_VERSION : __( "Unknown version", 'pdf-forms-for-woocommerce' ) ),
'current-plugin-version' => esc_html( self::VERSION ),
'supported-woocommerce-version' => esc_html( self::MAX_WC_VERSION ),
)
),
) );
if( $service = $this->get_service() )
{
$service->admin_notices();
if( $service != $this->pdf_ninja_service )
$this->pdf_ninja_service->admin_notices();
}
if( current_user_can( 'manage_woocommerce' ) )
{
// display previously logged admin messages
$messages = self::get_admin_messages();
if( count( $messages ) > 0 )
{
$messages = array_map( function( $message ) { return "<span class='".esc_attr($message['type'])."'>".esc_html($message['message'])."</span>"; }, $messages );
$messageHtml = self::render(
'admin-messages',
array(
'messages' => implode( '<br/>', $messages),
'clear-all-messages' => esc_html__( "Clear All Messages", 'pdf-forms-for-woocommerce' )
)
);
echo Pdf_Forms_For_WooCommerce::render_warning_notice( 'admin-messages-'.gmdate('Ymd'), array(
'label' => esc_html__( "PDF Forms Filler for WooCommerce Messages", 'pdf-forms-for-woocommerce' ),
'message' => $messageHtml,
) );
}
}
}
/**
* Checks if WooCommerce version is supported
*/
public function is_wc_version_supported( $version )
{
if( version_compare( $version, self::MIN_WC_VERSION ) < 0
|| version_compare( $version, self::MAX_WC_VERSION ) > 0 )
return false;
foreach( self::$BLACKLISTED_WC_VERSIONS as $blacklisted_version )
if( version_compare( $version, $blacklisted_version ) == 0 )
return false;
return true;
}
/**
* Returns the service module instance
*/
public function get_service()
{
$this->register_services();
if( ! $this->service )
$this->set_service( $this->load_pdf_ninja_service() );
return $this->service;
}
/**
* Sets the service module instance
*/
public function set_service( $service )
{
return $this->service = $service;
}
/**
* Loads and returns the storage module
*/
private static function get_storage()
{
require_once untrailingslashit( dirname( __FILE__ ) ) . '/src/filesystem/storage.php';
return Pdf_Forms_For_WooCommerce_Storage::get_instance();
}
/**
* Registers PDF.Ninja service
*/
public function register_services()
{
if( $this->registered_services )
return;
require_once untrailingslashit( dirname( __FILE__ ) ) . '/src/services/service.php';
$this->registered_services = true;
$this->load_pdf_ninja_service();
}
/**
* Loads the Pdf.Ninja service module
*/
private function load_pdf_ninja_service()
{
if( ! $this->pdf_ninja_service )
{
require_once untrailingslashit( dirname( __FILE__ ) ) . '/src/services/pdf-ninja.php';
$this->pdf_ninja_service = Pdf_Forms_For_WooCommerce_Pdf_Ninja::get_instance();
}
return $this->pdf_ninja_service;
}
/**
* Creates a new instance of the placeholder processor
*/
public function get_placeholder_processor()
{
require_once untrailingslashit( dirname( __FILE__ ) ) . '/src/integration/wc-placeholder-processor.php';
return new Pdf_Forms_For_WooCommerce_Placeholder_Processor();
}
/**
* Function for decoding metadata
*/
private static function decode_metadata( $data, $key = null )
{
if( ! empty( $data ) )
$data = json_decode( $data, true );
if( ! is_array( $data ) )
return null;
if( $key === null )
return $data;
if( isset( $data[$key] ) )
return $data[$key];
else
return null;
}
/**
* Function for retrieving metadata
*/
public static function get_metadata( $post_id, $key = null )
{
return self::decode_metadata( get_post_meta( $post_id, self::META_KEY, $single=true ), $key );
}
/**
* Function for retrieving order metadata
* $order can be either an instance of WC_Order, an instance of WP_Post or a numeric order/post ID
* $key is the metadata key for a specific metadata element
* If $key is null, the whole metadata store is returned
*/
public function get_order_metadata( $order, $key = null )
{
if( ! is_a( $order, 'WC_Order' ) )
{
$order = wc_get_order( $order );
if( ! is_a( $order, 'WC_Order' ) )
return null;
}
if( ! self::is_wc_hpos_enabled() )
return self::get_metadata( $order->get_id(), $key );
return self::decode_metadata( $order->get_meta( self::META_KEY, $single=true ), $key );
}
/**
* Function for updating metadata
*/
private static function update_metadata_array( $data, $key = null, $value = null )
{
if( $key === null )
$data = null;
else
{
if( $value === null )
{
if( isset( $data[$key] ) )
unset( $data[$key] );
}
else
$data[$key] = $value;
if( empty( $data ) )
$data = null;
else
$data['version'] = self::VERSION; // keep track of schema version
}
return $data;
}
/**
* Function for encoding metadata
*/
private static function encode_metadata( $data, $hpos = false )
{
$data = Pdf_Forms_For_WooCommerce_Wrapper::json_encode( $data );
if( !$hpos )
{
// wp bug workaround
// https://developer.wordpress.org/reference/functions/update_post_meta/#workaround
$data = wp_slash( $data );
}
return $data;
}
/**
* Function for setting metadata
* If $key is null, the whole metadata store is removed
* If $value is null, the metadata element with the given key is removed
*/
public static function set_metadata( $post_id, $key = null, $value = null )
{
// TODO: fix race condition
$data = self::get_metadata( $post_id );
$data = self::update_metadata_array( $data, $key, $value );
if( $data === null)
delete_post_meta( $post_id, self::META_KEY );
else
update_post_meta( $post_id, self::META_KEY, self::encode_metadata( $data ) );
return $value;
}
/**
* Function for setting order metadata
* $order can be either an instance of WC_Order, an instance of WP_Post or a numeric order/post ID
* If $key is null, the whole metadata store is removed
* If $value is null, the metadata element with the given key is removed
*/
public function set_order_metadata( $order, $key = null, $value = null )
{
$by_id = is_numeric( $order );
if( ! is_a( $order, 'WC_Order' ) )
{
// $order is probably order ID or post
$order = wc_get_order( $order );
if( ! is_a( $order, 'WC_Order' ) )
throw new Exception( __( "Invalid order", 'pdf-forms-for-woocommerce' ) );
}
if( ! self::is_wc_hpos_enabled() )
return self::set_metadata( $order->get_id(), $key, $value );
$data = $this->get_order_metadata( $order );
$new_data = self::update_metadata_array( $data, $key, $value );
// if metadata has changed, update it
if( $data != $new_data )
{
$data = $new_data;
if( $data === null)
$order->delete_meta_data( self::META_KEY );
else
$order->update_meta_data( self::META_KEY, self::encode_metadata( $data, true ) );
$order_id = $order->get_id();
if( ! isset( $this->do_not_save_orders[$order_id] ) )
{
if( $by_id )
$order->save();
else
{
// save after all changes have been made
if( $order_id )
{
if( count( $this->delayed_saving_orders ) == 0 )
add_action( 'shutdown', array( $this, 'save_delayed_orders' ) );
$this->delayed_saving_orders[$order_id] = $order;
}
}
}
}
return $value;
}
/**
* Function for delay-saving orders
* Used to avoid multiple unnecessary saves and other issues
*/
public function save_delayed_orders()
{
foreach( $this->delayed_saving_orders as $order )
$order->save();
$this->delayed_saving_orders = array();
}
/**
* Function for removing metadata
*/
public static function unset_metadata( $post_id, $key = null )
{
return self::set_metadata( $post_id, $key, null );
}
/**
* Function for removing order metadata
* $order can be either an instance of WC_Order, an instance of WP_Post or a numeric order/post ID
* If $key is null, the whole metadata store is removed
*/
public function unset_order_metadata( $order, $key = null )
{
return $this->set_order_metadata( $order, $key, null );
}
/**
* Hook that runs on user click 'Get New key' button and gets new pdf-ninja key
*/
public function wp_ajax_generate_pdf_ninja_key()
{
try
{
if( ! check_ajax_referer( 'pdf-forms-for-woocommerce-ajax-nonce', 'nonce', false ) )
throw new Exception( __( "Nonce mismatch", 'pdf-forms-for-woocommerce' ) );
if( ! current_user_can( 'manage_woocommerce' ) )
throw new Exception( __( "Permission denied", 'pdf-forms-for-woocommerce' ) );
$email = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : null;
if( ! $email )
throw new Exception( __( "Invalid email", 'pdf-forms-for-woocommerce' ) );
$service = $this->get_service();
$service->set_key( $key = $service->generate_key( $email ) );
}
catch ( Exception $e )
{
return wp_send_json( array (
'success' => false,
'error_message' => $e->getMessage()
) );
}
wp_send_json_success();
}
/**
* Used for clearing notice messages in wp-admin interface
*/
public function wp_ajax_clear_messages()
{
try
{
if( ! check_ajax_referer( 'pdf-forms-for-woocommerce-ajax-nonce', 'nonce', false ) )
throw new Exception( __( "Nonce mismatch", 'pdf-forms-for-woocommerce' ) );
if( ! current_user_can( 'manage_woocommerce' ) )
throw new Exception( __( "Permission denied", 'pdf-forms-for-woocommerce' ) );
self::clear_admin_messages();
}
catch ( Exception $e )
{
return wp_send_json( array (
'success' => false,
'error_message' => $e->getMessage()
) );
}
wp_send_json_success();
}
const DEFAULT_PDF_OPTIONS = array(
'skip_empty' => false,
'flatten' => false,
'email_templates' => array( 'customer_processing_order', 'customer_completed_order' ),
'filename' => "",
'save_directory'=> "",
'download_id' => "",
);
/**
* Returns MIME type of the file
*/
public static function get_mime_type( $filepath )
{
if( ! is_file( $filepath ) )
return null;
$mimetype = null;
if( function_exists( 'finfo_open' ) )
{
if( version_compare( phpversion(), "5.3" ) < 0 )
{
$finfo = finfo_open( FILEINFO_MIME );
if( $finfo )
{
$mimetype = finfo_file( $finfo, $filepath );
$mimetype = explode( ";", $mimetype );
$mimetype = reset( $mimetype );
finfo_close( $finfo );
}
}
else
{
$finfo = finfo_open( FILEINFO_MIME_TYPE );
if( $finfo )
{
$mimetype = finfo_file( $finfo, $filepath );
finfo_close( $finfo );
}
}
}
if( ! $mimetype && function_exists( 'mime_content_type' ) )
$mimetype = mime_content_type( $filepath );
// fallback
if( ! $mimetype )
{
$type = wp_check_filetype( $filepath );
if( isset( $type['type'] ) )
$mimetype = $type['type'];
}
if( ! $mimetype )
return 'application/octet-stream';
return $mimetype;
}
/**
* Downloads a file from the given URL and saves the contents to the given filepath, returns mime type via argument
*/
private static function download_file( $url, $filepath, &$mimetype = null )
{
// if this url points to the site, copy the file directly
$site_url = trailingslashit( get_site_url() );
if( substr( $url, 0, strlen( $site_url ) ) == $site_url )
{
$path = substr( $url, strlen( $site_url ) );
$home_path = trailingslashit( realpath( dirname(__FILE__) . '/../../../' ) );
$sourcepath = realpath( $home_path . $path );
if( $home_path && $sourcepath && substr( $sourcepath, 0, strlen( $home_path ) ) == $home_path )
if( is_file( $sourcepath ) )
if( copy($sourcepath, $filepath) )
{
$mimetype = self::get_mime_type( $sourcepath );
return;
}
}
$args = array(
'compress' => true,
'decompress' => true,
'timeout' => 100,
'redirection' => 5,
'user-agent' => 'pdf-forms-for-woocommerce/' . self::VERSION,
);
$response = wp_remote_get( $url, $args );
if( is_wp_error( $response ) )
throw new Exception(
self::replace_tags(
__( "Failed to download file: {error-message}", 'pdf-forms-for-woocommerce' ),
array( 'error-message' => $response->get_error_message() )
)
);
$mimetype = wp_remote_retrieve_header( $response, 'content-type' );
$body = wp_remote_retrieve_body( $response );
if( file_put_contents( $filepath, $body ) === false || ! is_file( $filepath ) )
throw new Exception( __( "Failed to create file", 'pdf-forms-for-woocommerce' ) );
}
/**
* Provides temporary file storage
*/
public function get_tmp_storage()
{
if( ! $this->tmp_storage )
{
// set up shutdown handler to clean up tmp dir on exit
add_action( 'shutdown', array( $this, 'remove_tmp_storage' ), 99, 0 );
$tmp_storage = self::get_storage();
$tmp_storage->set_subpath( 'pdf-forms-for-woocommerce/tmp/' . sanitize_file_name( wp_hash( wp_rand() . microtime() ) ) );
$this->tmp_storage = $tmp_storage;
$this->tmp_storage->initialize_path();
}
return $this->tmp_storage;
}
/**
* Removes temporary file storage
*/
public function remove_tmp_storage()
{
if( ! $this->tmp_storage )
return;
$this->tmp_storage->delete_subpath_recursively();
$this->tmp_storage = null;
remove_action( 'shutdown', array( $this, 'remove_tmp_storage' ), 99 );
}
/**
* Creates a temporary file path (but not the file itself)
*/
private function create_tmp_filepath( $subpath, $filename )
{
$uploads_dir = trailingslashit( $this->get_tmp_storage()->get_full_path() ) . $subpath;
wp_mkdir_p( $uploads_dir );
$filename = sanitize_file_name( $filename );
$filename = wp_unique_filename( $uploads_dir, $filename );
return trailingslashit( $uploads_dir ) . $filename;
}
/**
* Checks if the image MIME type is supported for embedding
*/
private function is_embed_image_format_supported( $mimetype )
{
$supported_mime_types = array(
"image/jpeg",
"image/png",
"image/gif",
"image/tiff",
"image/bmp",
"image/x-ms-bmp",
"image/svg+xml",
"image/webp",
);
if( $mimetype )
foreach( $supported_mime_types as $smt )
if( $mimetype === $smt )
return true;
return false;
}
/**
* Outputs order metabox
*/
public function display_order_metabox( $post_or_order_object = null )
{
print(
self::render( 'spinner' ) .
self::render(
'order-metabox',
array(
'reset-settings-instructions' => esc_html__( "Product settings are stored in orders when they are created. Resetting settings is necessary when new product settings need to be applied to an old order.", 'pdf-forms-for-woocommerce' ),
'reset-settings' => esc_html__( "Reset Settings", 'pdf-forms-for-woocommerce' ),
'reset-pdfs-instructions' => esc_html__( "PDFs are refilled when orders status changes. Sometimes you may want to manually trigger PDFs to be refilled after changing some aspect of the order, such as the billing address.", 'pdf-forms-for-woocommerce' ),
'reset-pdfs' => esc_html__( "Reset PDFs", 'pdf-forms-for-woocommerce' ),
)
)
);
}
/**
* Used for resetting order settings in wp-admin edit order interface
*/
public function wp_ajax_reset_order_settings()
{
try
{
if( ! check_ajax_referer( 'pdf-forms-for-woocommerce-ajax-nonce', 'nonce', false ) )
throw new Exception( __( "Nonce mismatch", 'pdf-forms-for-woocommerce' ) );
if( ! current_user_can( 'manage_woocommerce' ) )
throw new Exception( __( "Permission denied", 'pdf-forms-for-woocommerce' ) );
$order_id = isset( $_POST['order_id'] ) ? intval( $_POST['order_id'] ) : null;
if( ! $order_id )
throw new Exception( __( "Invalid order ID", 'pdf-forms-for-woocommerce' ) );
$order = wc_get_order( $order_id );
if( ! is_a( $order, 'WC_Order' ) )
throw new Exception( __( "Invalid order", 'pdf-forms-for-woocommerce' ) );
$this->reset_order_settings( $order );
}
catch ( Exception $e )
{
return wp_send_json( array (
'success' => false,
'error_message' => $e->getMessage()
) );
}
wp_send_json_success();
}
/**
* Used for resetting order pdfs in wp-admin edit order interface
*/
public function wp_ajax_reset_order_pdfs()
{
try
{
if( ! check_ajax_referer( 'pdf-forms-for-woocommerce-ajax-nonce', 'nonce', false ) )
throw new Exception( __( "Nonce mismatch", 'pdf-forms-for-woocommerce' ) );
if( ! current_user_can( 'manage_woocommerce' ) )
throw new Exception( __( "Permission denied", 'pdf-forms-for-woocommerce' ) );
$order_id = isset( $_POST['order_id'] ) ? intval( $_POST['order_id'] ) : null;
if( ! $order_id )
throw new Exception( __( "Invalid order ID", 'pdf-forms-for-woocommerce' ) );
$order = wc_get_order( $order_id );
if( ! is_a( $order, 'WC_Order' ) )
throw new Exception( __( "Invalid order", 'pdf-forms-for-woocommerce' ) );
// remove downloadable files
$this->unset_downloadable_files( $order );
// refilling is necessary only if PDFs are being saved in wp-uploads
$product_settings = $this->get_order_metadata( $order, 'product-settings' );
if( is_array( $product_settings ) && ! empty( $product_settings ) )
{
$placeholder_processor = $this->get_placeholder_processor();
$placeholder_processor->set_order( $order );
$items = $order->get_items();
foreach( $items as $item )
{
$order_item_id = $item->get_id();
$placeholder_processor->set_order_item( $item );
$product_id = $item->get_product_id();
$placeholder_processor->set_product_id( $product_id );
if( ! isset( $product_settings[$product_id] ) )
continue;
$settings = $product_settings[$product_id];
if( ! is_array( $settings )
|| ! isset( $settings['attachments'] )
|| ! is_array( $attachments = $settings['attachments'] ) )
continue;
foreach( $attachments as $attachment )
{
if( isset( $attachment['options'] )
&& is_array( $options = $attachment['options'] )
&& isset( $options['save_directory'] )
&& $options['save_directory'] !== "" )
{
$files = $this->fill_pdfs( $settings, $placeholder_processor );
break;
}
}
// clear temporary files
self::remove_tmp_storage();
}
}
}
catch ( Exception $e )
{
return wp_send_json( array (
'success' => false,
'error_message' => $e->getMessage()
) );
}
wp_send_json_success();
}
/**
* Keeps track of new orders
*/
public function woocommerce_new_order( $order_id, $order )
{
$this->new_orders[$order_id] = $order_id;
}
/**
* Remove outdated order files
*/
public function woocommerce_before_order_object_save( $order, $data_store )
{
// certain events cause downloadable files to become stale, such as when order status changes
// we need to delete the stale PDF files and recreate them
// however, we probalby don't want to keep redoing it over and over
// so, we should delete the old PDF files and recreate them later when needed
if( is_a( $order, 'WC_Order' ) )
{
// check if this order is in the database
$order_id = $order->get_id();
if( $order_id )
{
$new_status = $order->get_status();
$old_order = wc_get_order( $order_id );
$old_status = $old_order->get_status();
if( $old_status != $new_status )
{
// remove stale downloadable files
$this->unset_downloadable_files( $order );
}
}
}
}
/*
* Resets product settings for an order
* $order must be an instance of WC_Order
*/
private function reset_order_settings( $order )
{
// TODO: save copies of source PDF files in pdf-forms-for-woocommerce/pdf-cache directory in case they are deleted from media library and use the cached copy for this order
$product_settings = array();
$items = $order->get_items();
foreach( $items as $item )