-
Notifications
You must be signed in to change notification settings - Fork 0
/
pdf-forms-for-wpforms.php
2072 lines (1784 loc) · 69.9 KB
/
pdf-forms-for-wpforms.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 WPForms
* Plugin URI: https://pdfformsfiller.org/
* Description: Build WPForms from PDF forms. Get PDFs filled automatically and attached to email messages and/or website responses on form submissions.
* Version: 1.1.10
* Requires at least: 5.4
* Requires PHP: 5.5
* Author: Maximum.Software
* Author URI: https://maximum.software/
* Text Domain: pdf-forms-for-wpforms
* Domain Path: /languages
* License: GPLv3
* License URI: https://www.gnu.org/licenses/gpl-3.0.html
*/
if( ! defined( 'ABSPATH' ) )
return;
require_once untrailingslashit( dirname( __FILE__ ) ) . '/inc/tgm-config.php';
require_once untrailingslashit( dirname( __FILE__ ) ) . '/modules/wrapper.php';
if( ! class_exists('Pdf_Forms_For_WPForms') )
{
class Pdf_Forms_For_WPForms
{
const VERSION = '1.1.10';
const MIN_WPFORMS_VERSION = '1.6.9';
const MAX_WPFORMS_VERSION = '1.9.99';
private static $BLACKLISTED_WPFORMS_VERSIONS = array();
private static $instance = null;
private $pdf_ninja_service = null;
private $service = null;
private $registered_services = false;
private $downloads = null;
private $storage = null;
private $tmp_dir = null;
private $wpforms_mail_attachments = 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' ) );
register_activation_hook( __FILE__, array( $this, 'plugin_activated' ) );
register_deactivation_hook( __FILE__, array( $this, 'plugin_deactivated' ) );
add_action( 'pdf_forms_for_wpforms_cron', array( $this, 'cron' ) );
}
/**
* 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('WPForms') || ! defined( 'WPFORMS_VERSION' ) )
return;
add_action( 'wp_ajax_pdf_forms_for_wpforms_get_attachment_data', array( $this, 'wp_ajax_get_attachment_data' ) );
add_action( 'wp_ajax_pdf_forms_for_wpforms_query_page_image', array( $this, 'wp_ajax_query_page_image' ) );
add_action( 'wp_ajax_pdf_forms_for_wpforms_generate_pdf_ninja_key', array( $this, 'wp_ajax_generate_pdf_ninja_key') );
add_action( 'admin_menu', array( $this, 'register_services' ) );
add_filter( 'wpforms_save_form_args', array( $this, 'wpforms_save_form_args' ), 10, 3 );
add_action( 'wpforms_process', array( $this, 'fill_pdfs' ), 10, 3 );
add_action( 'wpforms_process_complete', array( $this, 'remove_tmp_dir' ), 99, 0 );
add_filter( 'wpforms_emails_send_email_data', array( $this, 'attach_files' ), 10, 2 );
add_action( 'wpforms_frontend_confirmation_message', array( $this, 'change_confirmation_message'), 10, 4 );
add_filter( 'wpforms_builder_settings_sections', array( $this, 'add_settings_panel' ) );
add_action( 'wpforms_form_settings_panel_content', array( $this, 'add_settings_content' ) );
add_filter( 'cron_schedules', array( $this, 'cron_schedules' ) );
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-wpforms', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
/*
* Runs after the plugin have been activated/deactivated
*/
public function plugin_activated( $network_wide = false )
{
if( $network_wide )
{
$sites = get_sites( array( 'fields' => 'ids' ) );
foreach( $sites as $id )
{
switch_to_blog( $id );
$this->plugin_activated( false );
restore_current_blog();
}
return;
}
$this->enable_cron();
}
public function plugin_deactivated( $network_deactivating = false )
{
if( $network_deactivating )
{
$sites = get_sites( array( 'fields' => 'ids' ) );
foreach( $sites as $id )
{
switch_to_blog( $id );
$this->plugin_deactivated( false );
restore_current_blog();
}
return;
}
$this->disable_cron();
$this->get_downloads()->set_timeout(0)->delete_old_downloads();
}
/*
* Hook that adds a cron schedule
*/
public function cron_schedules( $schedules )
{
$interval = $this->get_downloads()->get_timeout();
$display = self::replace_tags( __("Every {interval} seconds"), array( 'interval' => $interval ) );
$schedules['pdf_forms_for_wpforms_cron_frequency'] = array(
'interval' => $interval,
'display' => $display
);
return $schedules;
}
/*
* Enables cron
*/
private function enable_cron()
{
$due = wp_next_scheduled( 'pdf_forms_for_wpforms_cron' );
$current_time = time();
$interval = $this->get_downloads()->get_timeout();
if( $due !== false && (
$due < $current_time - ( $interval + 60 ) // cron is not functional
|| $due > $current_time + $interval // interval changed to a smaller value
) )
{
$this->cron(); // run manually
wp_clear_scheduled_hook( 'pdf_forms_for_wpforms_cron' );
$due = false;
}
if( $due === false )
wp_schedule_event( $current_time, 'pdf_forms_for_wpforms_cron_frequency', 'pdf_forms_for_wpforms_cron' );
}
/*
* Disables cron
*/
private function disable_cron()
{
wp_clear_scheduled_hook( 'pdf_forms_for_wpforms_cron' );
}
/**
* Executes scheduled tasks
*/
public function cron()
{
$this->get_downloads()->delete_old_downloads();
}
/**
* Adds plugin action links
*/
public function action_links( $links )
{
$links[] = '<a target="_blank" href="https://wordpress.org/support/plugin/pdf-forms-for-wpforms/">'.esc_html__( "Support", 'pdf-forms-for-wpforms' ).'</a>';
return $links;
}
/**
* Prints admin notices
*/
public function admin_notices()
{
if( ! class_exists('WPForms') || ! defined( 'WPFORMS_VERSION' ) )
{
if( current_user_can( 'activate_plugins' ) )
echo Pdf_Forms_For_WPForms::render_error_notice( 'wpf-not-installed', array(
'label' => esc_html__( "PDF Forms Filler for WPForms Error", 'pdf-forms-for-wpforms' ),
'message' => esc_html__( "The required plugin 'WPForms' version is not installed!", 'pdf-forms-for-wpforms' ),
) );
return;
}
if( ! $this->is_wpf_version_supported( WPFORMS_VERSION ) )
if( current_user_can( 'activate_plugins' ) )
echo Pdf_Forms_For_WPForms::render_warning_notice( 'unsupported-wpf-version-'.WPFORMS_VERSION, array(
'label' => esc_html__( "PDF Forms Filler for WPForms Warning", 'pdf-forms-for-wpforms' ),
'message' =>
self::replace_tags(
esc_html__( "The currently installed version of 'WPForms' plugin ({current-wpforms-version}) may not be supported by the current version of 'PDF Forms Filler for WPForms' plugin ({current-plugin-version}), please switch to 'WPForms' plugin version {supported-wpforms-version} or below to ensure that 'PDF Forms Filler for WPForms' plugin would work correctly.", 'pdf-forms-for-wpforms' ),
array(
'current-wpforms-version' => esc_html( defined( 'WPFORMS_VERSION' ) ? WPFORMS_VERSION : __( "Unknown version", 'pdf-forms-for-wpforms' ) ),
'current-plugin-version' => esc_html( self::VERSION ),
'supported-wpforms-version' => esc_html( self::MAX_WPFORMS_VERSION ),
)
),
) );
if( $service = $this->get_service() )
{
$service->admin_notices();
if( $service != $this->pdf_ninja_service )
$this->pdf_ninja_service->admin_notices();
}
}
/**
* Checks if WPF version is supported
*/
public function is_wpf_version_supported( $version )
{
if( version_compare( $version, self::MIN_WPFORMS_VERSION ) < 0
|| version_compare( $version, self::MAX_WPFORMS_VERSION ) > 0 )
return false;
foreach( self::$BLACKLISTED_WPFORMS_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 function get_storage()
{
if( ! $this->storage )
{
require_once untrailingslashit( dirname( __FILE__ ) ) . '/modules/storage.php';
$this->storage = Pdf_Forms_For_WPForms_Storage::get_instance();
}
return $this->storage;
}
/**
* Loads and returns the downloads module
*/
private function get_downloads()
{
if( ! $this->downloads )
{
require_once untrailingslashit( dirname( __FILE__ ) ) . '/modules/downloads.php';
$this->downloads = Pdf_Forms_For_WPForms_Downloads::get_instance();
}
return $this->downloads;
}
/**
* Registers PDF.Ninja service
*/
public function register_services()
{
if( $this->registered_services )
return;
require_once untrailingslashit( dirname( __FILE__ ) ) . '/modules/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__ ) ) . '/modules/pdf-ninja.php';
$this->pdf_ninja_service = WPForms_Pdf_Ninja::get_instance();
}
return $this->pdf_ninja_service;
}
/**
* Function for working with metadata
*/
public static function get_meta( $post_id, $key )
{
$value = get_post_meta( $post_id, "pdf-forms-for-wpforms-" . $key, $single=true );
if( $value === '' )
return null;
return $value;
}
/**
* Function for working with metadata
*/
public static function set_meta( $post_id, $key, $value )
{
$oldval = get_post_meta( $post_id, "pdf-forms-for-wpforms-" . $key, true );
if( $oldval !== '' && $value === null)
delete_post_meta( $post_id, "pdf-forms-for-wpforms-" . $key );
else
{
// wp bug workaround
// https://developer.wordpress.org/reference/functions/update_post_meta/#workaround
$fixed_value = wp_slash( $value );
update_post_meta( $post_id, "pdf-forms-for-wpforms-" . $key, $fixed_value, $oldval );
}
return $value;
}
/**
* Function for working with metadata
*/
public static function unset_meta( $post_id, $key )
{
delete_post_meta( $post_id, "pdf-forms-for-wpforms-" . $key );
}
/**
* 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-wpforms-ajax-nonce', 'nonce', false ) )
throw new Exception( __( "Nonce mismatch", 'pdf-forms-for-wpforms' ) );
if( ! wpforms_current_user_can( wpforms_get_capability_manage_options() ) )
throw new Exception( __( "Permission denied", 'pdf-forms-for-wpforms' ) );
$service = $this->get_service();
// TODO: get email from form, remove email setting
if( empty( $email = wpforms_setting( WPForms_Pdf_Ninja::VIEW . '-email' ) ) )
$email = null;
else
$email = sanitize_email( $email );
$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();
}
const DEFAULT_PDF_OPTIONS = array( 'skip_empty' => false, 'flatten' => false, 'notifications' => array( ), 'confirmations' => array(), 'filename' => "", 'save_directory'=> "" );
/**
* Hook that runs on wpform save action to validate plugin data
*/
public function wpforms_save_form_args( $post, $form_data, $args )
{
try
{
$post_content = json_decode( stripslashes( $post['post_content'] ), true );
if( ! is_array( $post_content ) )
throw new Exception(
__( "Missing post content", 'pdf-forms-for-wpforms' ),
);
// check form settings
if( isset( $post_content['pdf-forms-for-wpforms-form-settings'] ) && isset( $post_content['pdf-forms-for-wpforms-form-settings']['data'] ) )
{
$data = self::decode_form_settings( $post_content['pdf-forms-for-wpforms-form-settings']['data'] );
if( isset( $post_content['settings'] ) )
$wpf_settings = $post_content['settings'];
if( ! is_array( $wpf_settings ) )
$wpf_settings = array();
if( isset( $wpf_settings['notifications'] ) )
$wpf_notifications = $wpf_settings['notifications'];
if( ! is_array( $wpf_notifications ) )
$wpf_notifications = array();
if( isset( $wpf_settings['confirmations'] ) )
$wpf_confirmations = $wpf_settings['confirmations'];
if( ! is_array( $wpf_confirmations ) )
$wpf_confirmations = array();
if( isset( $post_content['fields'] ) )
$wpf_fields = $post_content['fields'];
if( ! is_array( $wpf_fields ) )
$wpf_fields = array();
// check attachments
$attachments = array();
if( isset( $data['attachments'] ) && is_array( $data['attachments'] ) )
{
foreach( $data['attachments'] as $attachment )
{
$attachment_id = $attachment['attachment_id'];
// check permissions
if( ! wpforms_current_user_can( 'edit_post', $attachment_id ) )
continue;
// check options
if( !isset( $attachment['options'] ) || !is_array( $attachment['options'] ) )
$attachment['options'] = array();
else
{
// add missing options
foreach( self::DEFAULT_PDF_OPTIONS as $option_name => $option_value )
{
if( !isset( $attachment['options'][$option_name] ) )
$attachment['options'][$option_name] = $option_value;
}
// remove non-existing options
foreach( $attachment['options'] as $option_name => $option_value )
{
if( !isset( self::DEFAULT_PDF_OPTIONS[$option_name] ) )
unset( $attachment['options'][$option_name] );
}
// check skip_empty to make sure it is a boolean value
if( isset( $attachment['options']['skip_empty'] ) && !is_bool( $attachment['options']['skip_empty'] ) )
$attachment['options']['skip_empty'] = boolval( $attachment['options']['skip_empty'] );
// check flatten to make sure it is a boolean value
if( isset( $attachment['options']['flatten'] ) && !is_bool( $attachment['options']['flatten'] ) )
$attachment['options']['flatten'] = boolval( $attachment['options']['flatten'] );
// check notifications
if( isset( $attachment['options']['notifications'] ) )
{
$option_value = $attachment['options']['notifications'];
if( !is_array( $option_value ) )
$option_value = array();
foreach( $option_value as $notification_id => $notification )
{
// check to make sure this notification is valid
if( ! isset($wpf_notifications[$notification] ) )
unset( $attachment['options']['notifications'][$notification_id] );
}
}
// check confirmations
if( isset( $attachment['options']['confirmations'] ) )
{
$option_value = $attachment['options']['confirmations'];
if( !is_array( $option_value ) )
$option_value = array();
foreach( $option_value as $confirmation_id => $confirmation )
{
// check to make sure this confirmation is valid
if( ! isset( $wpf_confirmations[$confirmation] ) )
unset( $attachment['options']['confirmations'][$confirmation_id] );
}
}
}
$attachments[$attachment_id] = $attachment;
}
}
$data['attachments'] = $attachments;
// process mappings
$mappings = array();
if( isset( $data['mappings'] ) && is_array( $data['mappings'] ) )
{
foreach( $data['mappings'] as $mapping )
{
if( isset( $mapping['wpf_field'] ) && isset( $mapping['pdf_field'] ) )
{
// make sure wpforms field exists
$exists = false;
foreach( $wpf_fields as $field )
if( isset( $field['id'] ) && $field['id'] == $mapping['wpf_field'] )
{
$exists = true;
break;
}
if( ! $exists )
continue;
// TODO: make sure pdf field exists
$mappings[] = array( 'wpf_field' => $mapping['wpf_field'], 'pdf_field' => $mapping['pdf_field'] );
}
if( isset( $mapping['smart_tags'] ) && isset( $mapping['pdf_field'] ) )
{
$mappings[] = array( 'smart_tags' => $mapping['smart_tags'], 'pdf_field' => $mapping['pdf_field'] );
}
}
}
$data['mappings'] = $mappings;
// process embeds
$embeds = array();
if( isset( $data['embeds'] ) && is_array( $data['embeds'] ) )
{
foreach( $data['embeds'] as $embed )
{
if( ! isset( $embed['attachment_id'] ) )
continue;
if( ! isset( $embed['smart_tags'] ) && ! isset( $embed['wpf_field'] ) )
continue;
// make sure attachment exists
if( ! isset( $data['attachments'][ $embed['attachment_id'] ] ) && $embed['attachment_id'] !== 'all' )
continue;
if( isset( $embed['wpf_field'] ) )
{
// make sure wpforms field exists
$exists = false;
foreach( $wpf_fields as $field )
if( isset( $field['id'] ) && $field['id'] == $embed['wpf_field'] )
{
$exists = true;
break;
}
if( ! $exists )
continue;
}
// TODO: make sure pdf page exists
// TODO: check insertion position and size
if( isset( $embed['smart_tags'] ) )
$embed['smart_tags'] = strval( $embed['smart_tags'] );
// TODO: don't reuse user input but create a new array with checked data
$embeds[] = $embed;
}
}
$data['embeds'] = $embeds;
// process value mappings
if( !isset( $data['value_mappings'] ) || !is_array( $data['value_mappings'] ) )
$data['value_mappings'] = array();
else
{
$value_mappings = array();
foreach( $data['value_mappings'] as $value_mapping )
if( isset( $value_mapping['pdf_field'] ) && isset( $value_mapping['wpf_value'] ) && isset( $value_mapping['pdf_value'] ) )
$value_mappings[] = array( 'pdf_field' => $value_mapping['pdf_field'], 'wpf_value' => $value_mapping['wpf_value'], 'pdf_value' => $value_mapping['pdf_value'] );
$data['value_mappings'] = $value_mappings;
}
$post_content['pdf-forms-for-wpforms-form-settings']['data'] = self::encode_form_settings( $data );
}
$post['post_content'] = wpforms_encode( $post_content );
return $post;
}
catch(Exception $e)
{
// TODO: improve error handling via wpforms
wp_send_json_error(
esc_html(
self::replace_tags(
__( "Error saving PDF form data: {error-message} at {error-file}:{error-line}", 'pdf-forms-for-wpforms' ),
array( 'error-message' => $e->getMessage(), 'error-file' => wp_basename( $e->getFile() ), 'error-line' => $e->getLine() )
)
)
);
exit(0);
}
}
/**
* 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-wpforms/' . 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-wpforms' ),
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-wpforms' ) );
}
/**
* Get temporary directory path
*/
public static function get_tmp_path()
{
$upload_dir = wpforms_upload_dir();
$tmp_path = empty( $upload_dir['error'] ) ? ( trailingslashit( $upload_dir['path'] ) . 'tmp' ) : get_temp_dir();
$dir = trailingslashit( $tmp_path ) . 'pdf-forms-for-wpforms';
if( ! is_dir( $dir ) )
{
wp_mkdir_p( $dir );
wpforms_create_index_html_file( $dir );
}
return trailingslashit( $dir );
}
/**
* Creates a temporary directory
*/
public function create_tmp_dir()
{
if( ! $this->tmp_dir )
{
$dir = trailingslashit( self::get_tmp_path() ) . wp_hash( wp_rand() . microtime() );
wp_mkdir_p( $dir );
$this->tmp_dir = trailingslashit( $dir );
}
return $this->tmp_dir;
}
/**
* Removes a temporary directory
*/
public function remove_tmp_dir()
{
if( ! $this->tmp_dir )
return;
// remove files in the directory
$tmp_dir_slash = trailingslashit( $this->tmp_dir );
$files = array_merge( glob( $tmp_dir_slash . '*' ), glob( $tmp_dir_slash . '.*' ) );
while( $file = array_shift( $files ) )
if( is_file( $file ) )
@unlink( $file );
@rmdir( $this->tmp_dir );
$this->tmp_dir = null;
}
/**
* Creates a temporary file path (but not the file itself)
*/
private function create_tmp_filepath( $filename )
{
$uploads_dir = $this->create_tmp_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;
}
/**
* Used for encoding WPForms form settings data
*/
public static function encode_form_settings( $data )
{
return base64_encode( self::json_encode( $data ) );
}
/**
* Used for decoding WPForms form settings data
*/
public static function decode_form_settings( $data )
{
$form_settings = array();
// we can't use json directly, we have to use encoding without slashes and quotes due to an unnecessary stripslashes() call in wpforms/includes/admin/builder/panels/class-base.php
if( is_array( $base64_decoded = json_decode( base64_decode( $data ), true ) ) )
$form_settings = $base64_decoded;
else
if( is_array( $json_decoded = json_decode( $data, true ) ) )
$form_settings = $json_decoded;
return $form_settings;
}
/**
* We need to fill the pdf's document fields and then create attachment file and attach them
*/
public function fill_pdfs( $wpform_fields, $entry, $form_data )
{
try
{
$entry_id = $entry["id"];
$wpform_fields_data = $entry['fields'];
$attachments = array();
$mappings = array();
$embeds = array();
$value_mappings = array();
if( isset( $form_data['pdf-forms-for-wpforms-form-settings'] ) && isset( $form_data['pdf-forms-for-wpforms-form-settings']['data'] ) )
{
$form_settings = self::decode_form_settings( $form_data['pdf-forms-for-wpforms-form-settings']['data'] );
if( isset( $form_settings['attachments'] ) && is_array( $form_settings['attachments'] ) )
$attachments = $form_settings['attachments'];
if( isset( $form_settings['mappings'] ) && is_array( $form_settings['mappings'] ) )
$mappings = $form_settings['mappings'];
if( isset( $form_settings['embeds'] ) && is_array( $form_settings['embeds'] ) )
$embeds = $form_settings['embeds'];
if( isset( $form_settings['value_mappings'] ) && is_array( $form_settings['value_mappings'] ))
$value_mappings = $form_settings['value_mappings'];
}
$files = array();
// preprocess embedded images
$embed_files = array();
foreach( $embeds as $id => $embed )
{
$filepath = null;
$filename = null;
$url_mimetype = null;
$url = null;
if( isset( $embed["wpf_field"] ) )
{
$wpf_field_id = $embed["wpf_field"];
$url = $wpform_fields_data[$wpf_field_id];
}
if( isset( $embed['smart_tags'] ) )
{
$url = wpforms_process_smart_tags( $embed["smart_tags"], $form_data, $wpform_fields, $entry_id );
}
if( $url != null )
{
if( filter_var( $url, FILTER_VALIDATE_URL ) !== FALSE )
if( substr( $url, 0, 5 ) === 'http:' || substr( $url, 0, 6 ) === 'https:' )
{
$filepath = $this->create_tmp_filepath( 'img_download_'.count($embed_files).'.tmp' );
self::download_file( $url, $filepath, $url_mimetype ); // can throw an exception
$filename = $url;
}
if( substr( $url, 0, 5 ) === 'data:' )
{
$filepath = $this->create_tmp_filepath( 'img_data_'.count($embed_files).'.tmp' );
$filename = $url;
$parsed = self::parse_data_uri( $url );
if( $parsed !== false )
{
$url_mimetype = $parsed['mime'];
if( file_put_contents( $filepath, $parsed['data'] ) === false || ! is_file( $filepath ) )
throw new Exception( __( "Failed to create file", 'pdf-forms-for-wpforms' ) );
}
}
}
if( isset( $embed["wpf_field"] ) )
{
$wpf_field_id = $embed["wpf_field"];
$field = null;
if( isset( $form_data['fields'][$wpf_field_id] ) )
{
$field = $form_data['fields'][$wpf_field_id];
if( is_array( $field ) && $field['type'] == 'file-upload' )
{
$input_name = sprintf( 'wpforms_%d_%d', $entry_id, $field['id'] );
if( $field['style'] == 'modern' && isset( $_POST[$input_name] ) )
{
$raw_files = json_decode( wp_unslash( $_POST[$input_name] ), true );
if( is_array( $raw_files ) && sizeof( $raw_files ) > 0 )
{
// TODO: handle multiple files
$file = reset( $raw_files );
$upload_dir = wpforms_upload_dir();
$upload_path = trailingslashit( $upload_dir['path'] ) . 'tmp';
$upload_filepath = trailingslashit( $upload_path ) . wp_basename( $file['file'] );
// security check
$upload_filepath = realpath( $upload_filepath );
$upload_path = realpath( $upload_path );
if( $upload_filepath !== false && $upload_path !== false
&& substr( $upload_filepath, 0, strlen( $upload_path ) ) === $upload_path )
{
$filepath = $upload_filepath;
$filename = $file['file_user_name'];
}
}
}
else if( ! empty( $_FILES[$input_name] ) )
{
$filepath = $_FILES[$input_name]['tmp_name'];
$filename = $_FILES[$input_name]['name'];
}
}
}
}
if( ! $filepath )
continue;
$file_mimetype = self::get_mime_type( $filepath );
$mimetype_supported = false;
$mimetype = 'unknown';
if( $file_mimetype )
{
$mimetype = $file_mimetype;
// check if MIME type is supported based on file contents
$mimetype_supported = $this->is_embed_image_format_supported( $file_mimetype );
}
// if we were not able to determine MIME type based on file contents
// then fall back to URL MIME type (if we are dealing with a URL)
// (maybe fileinfo functions are not functional and WP fallback failed due to the ".tmp" extension)
if( !$mimetype_supported && $url_mimetype )
{
$mimetype = $url_mimetype;
$mimetype_supported = $this->is_embed_image_format_supported( $url_mimetype );
}
if( !$mimetype_supported )
throw new Exception(
self::replace_tags(
__( "File type {mime-type} of {file} is unsupported for {purpose}", 'pdf-forms-for-wpforms' ),
array( 'mime-type' => $mimetype, 'file' => $filename, 'purpose' => __( "image embedding", 'pdf-forms-for-wpforms') )
)
);
$embed_files[$id] = $filepath;
}
$multiselectable_wpform_fields = array();
foreach( $wpform_fields as $wpform_field )
if( array_key_exists( 'name', $wpform_field ) )
{
if(
// WPForms checkboxes can have multiple values if the choice limit is more than one
( $wpform_field['type'] == 'checkbox' && intval( $form_data['fields'][$wpform_field['id']]['choice_limit'] ) != 1 )
// WPForms drop-downs can have 'multiple' option