-
Notifications
You must be signed in to change notification settings - Fork 801
/
grunion-contact-form.php
2756 lines (2334 loc) · 90.2 KB
/
grunion-contact-form.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: Grunion Contact Form
Description: Add a contact form to any post, page or text widget. Emails will be sent to the post's author by default, or any email address you choose. As seen on WordPress.com.
Plugin URI: http://automattic.com/#
AUthor: Automattic, Inc.
Author URI: http://automattic.com/
Version: 2.4
License: GPLv2 or later
*/
define( 'GRUNION_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'GRUNION_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
if ( is_admin() ) {
require_once GRUNION_PLUGIN_DIR . 'admin.php';
}
add_action( 'rest_api_init', 'grunion_contact_form_require_endpoint' );
function grunion_contact_form_require_endpoint() {
require_once GRUNION_PLUGIN_DIR . 'class-grunion-contact-form-endpoint.php';
}
/**
* Sets up various actions, filters, post types, post statuses, shortcodes.
*/
class Grunion_Contact_Form_Plugin {
/**
* @var string The Widget ID of the widget currently being processed. Used to build the unique contact-form ID for forms embedded in widgets.
*/
public $current_widget_id;
static $using_contact_form_field = false;
static function init() {
static $instance = false;
if ( ! $instance ) {
$instance = new Grunion_Contact_Form_Plugin;
// Schedule our daily cleanup
add_action( 'wp_scheduled_delete', array( $instance, 'daily_akismet_meta_cleanup' ) );
}
return $instance;
}
/**
* Runs daily to clean up spam detection metadata after 15 days. Keeps your DB squeaky clean.
*/
public function daily_akismet_meta_cleanup() {
global $wpdb;
$feedback_ids = $wpdb->get_col( "SELECT p.ID FROM {$wpdb->posts} as p INNER JOIN {$wpdb->postmeta} as m on m.post_id = p.ID WHERE p.post_type = 'feedback' AND m.meta_key = '_feedback_akismet_values' AND DATE_SUB(NOW(), INTERVAL 15 DAY) > p.post_date_gmt LIMIT 10000" );
if ( empty( $feedback_ids ) ) {
return;
}
foreach ( $feedback_ids as $feedback_id ) {
delete_post_meta( $feedback_id, '_feedback_akismet_values' );
}
}
/**
* Strips HTML tags from input. Output is NOT HTML safe.
*
* @param mixed $data_with_tags
* @return mixed
*/
public static function strip_tags( $data_with_tags ) {
if ( is_array( $data_with_tags ) ) {
foreach ( $data_with_tags as $index => $value ) {
$index = sanitize_text_field( strval( $index ) );
$value = wp_kses( strval( $value ), array() );
$value = str_replace( '&', '&', $value ); // undo damage done by wp_kses_normalize_entities()
$data_without_tags[ $index ] = $value;
}
} else {
$data_without_tags = wp_kses( $data_with_tags, array() );
$data_without_tags = str_replace( '&', '&', $data_without_tags ); // undo damage done by wp_kses_normalize_entities()
}
return $data_without_tags;
}
function __construct() {
$this->add_shortcode();
// While generating the output of a text widget with a contact-form shortcode, we need to know its widget ID.
add_action( 'dynamic_sidebar', array( $this, 'track_current_widget' ) );
// Add a "widget" shortcode attribute to all contact-form shortcodes embedded in widgets
add_filter( 'widget_text', array( $this, 'widget_atts' ), 0 );
// If Text Widgets don't get shortcode processed, hack ours into place.
if ( ! has_filter( 'widget_text', 'do_shortcode' ) ) {
add_filter( 'widget_text', array( $this, 'widget_shortcode_hack' ), 5 );
}
// Akismet to the rescue
if ( defined( 'AKISMET_VERSION' ) || function_exists( 'akismet_http_post' ) ) {
add_filter( 'jetpack_contact_form_is_spam', array( $this, 'is_spam_akismet' ), 10, 2 );
add_action( 'contact_form_akismet', array( $this, 'akismet_submit' ), 10, 2 );
}
add_action( 'loop_start', array( 'Grunion_Contact_Form', '_style_on' ) );
add_action( 'wp_ajax_grunion-contact-form', array( $this, 'ajax_request' ) );
add_action( 'wp_ajax_nopriv_grunion-contact-form', array( $this, 'ajax_request' ) );
// Export to CSV feature
if ( is_admin() ) {
add_action( 'admin_init', array( $this, 'download_feedback_as_csv' ) );
add_action( 'admin_footer-edit.php', array( $this, 'export_form' ) );
add_action( 'admin_menu', array( $this, 'admin_menu' ) );
add_action( 'current_screen', array( $this, 'unread_count' ) );
}
// custom post type we'll use to keep copies of the feedback items
register_post_type( 'feedback', array(
'labels' => array(
'name' => __( 'Feedback', 'jetpack' ),
'singular_name' => __( 'Feedback', 'jetpack' ),
'search_items' => __( 'Search Feedback', 'jetpack' ),
'not_found' => __( 'No feedback found', 'jetpack' ),
'not_found_in_trash' => __( 'No feedback found', 'jetpack' ),
),
'menu_icon' => 'dashicons-feedback',
'show_ui' => TRUE,
'show_in_admin_bar' => FALSE,
'public' => FALSE,
'rewrite' => FALSE,
'query_var' => FALSE,
'capability_type' => 'page',
'show_in_rest' => true,
'rest_controller_class' => 'Grunion_Contact_Form_Endpoint',
'capabilities' => array(
'create_posts' => false,
'publish_posts' => 'publish_pages',
'edit_posts' => 'edit_pages',
'edit_others_posts' => 'edit_others_pages',
'delete_posts' => 'delete_pages',
'delete_others_posts' => 'delete_others_pages',
'read_private_posts' => 'read_private_pages',
'edit_post' => 'edit_page',
'delete_post' => 'delete_page',
'read_post' => 'read_page',
),
'map_meta_cap' => true,
) );
// Add to REST API post type whitelist
add_filter( 'rest_api_allowed_post_types', array( $this, 'allow_feedback_rest_api_type' ) );
// Add "spam" as a post status
register_post_status( 'spam', array(
'label' => 'Spam',
'public' => false,
'exclude_from_search' => true,
'show_in_admin_all_list' => false,
'label_count' => _n_noop( 'Spam <span class="count">(%s)</span>', 'Spam <span class="count">(%s)</span>', 'jetpack' ),
'protected' => true,
'_builtin' => false,
) );
// POST handler
if (
isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' == strtoupper( $_SERVER['REQUEST_METHOD'] )
&&
isset( $_POST['action'] ) && 'grunion-contact-form' == $_POST['action']
&&
isset( $_POST['contact-form-id'] )
) {
add_action( 'template_redirect', array( $this, 'process_form_submission' ) );
}
/*
Can be dequeued by placing the following in wp-content/themes/yourtheme/functions.php
*
* function remove_grunion_style() {
* wp_deregister_style('grunion.css');
* }
* add_action('wp_print_styles', 'remove_grunion_style');
*/
if ( is_rtl() ) {
wp_register_style( 'grunion.css', GRUNION_PLUGIN_URL . 'css/rtl/grunion-rtl.css', array(), JETPACK__VERSION );
} else {
wp_register_style( 'grunion.css', GRUNION_PLUGIN_URL . 'css/grunion.css', array(), JETPACK__VERSION );
}
}
/**
* Add the 'Export' menu item as a submenu of Feedback.
*/
public function admin_menu() {
add_submenu_page(
'edit.php?post_type=feedback',
__( 'Export feedback as CSV', 'jetpack' ),
__( 'Export CSV', 'jetpack' ),
'export',
'feedback-export',
array( $this, 'export_form' )
);
}
/**
* Add to REST API post type whitelist
*/
function allow_feedback_rest_api_type( $post_types ) {
$post_types[] = 'feedback';
return $post_types;
}
/**
* Display the count of new feedback entries received. It's reset when user visits the Feedback screen.
*
* @since 4.1.0
*
* @param object $screen Information about the current screen.
*/
function unread_count( $screen ) {
if ( isset( $screen->post_type ) && 'feedback' == $screen->post_type ) {
update_option( 'feedback_unread_count', 0 );
} else {
global $menu;
if ( isset( $menu ) && is_array( $menu ) && ! empty( $menu ) ) {
foreach ( $menu as $index => $menu_item ) {
if ( 'edit.php?post_type=feedback' == $menu_item[2] ) {
$unread = get_option( 'feedback_unread_count', 0 );
if ( $unread > 0 ) {
$unread_count = current_user_can( 'publish_pages' ) ? " <span class='feedback-unread count-{$unread} awaiting-mod'><span class='feedback-unread-count'>" . number_format_i18n( $unread ) . '</span></span>' : '';
$menu[ $index ][0] .= $unread_count;
}
break;
}
}
}
}
}
/**
* Handles all contact-form POST submissions
*
* Conditionally attached to `template_redirect`
*/
function process_form_submission() {
// Add a filter to replace tokens in the subject field with sanitized field values
add_filter( 'contact_form_subject', array( $this, 'replace_tokens_with_input' ), 10, 2 );
$id = stripslashes( $_POST['contact-form-id'] );
$hash = isset( $_POST['contact-form-hash'] ) ? $_POST['contact-form-hash'] : null;
$hash = preg_replace( '/[^\da-f]/i', '', $hash );
if ( is_user_logged_in() ) {
check_admin_referer( "contact-form_{$id}" );
}
$is_widget = 0 === strpos( $id, 'widget-' );
$form = false;
if ( $is_widget ) {
// It's a form embedded in a text widget
$this->current_widget_id = substr( $id, 7 ); // remove "widget-"
$widget_type = implode( '-', array_slice( explode( '-', $this->current_widget_id ), 0, -1 ) ); // Remove trailing -#
// Is the widget active?
$sidebar = is_active_widget( false, $this->current_widget_id, $widget_type );
// This is lame - no core API for getting a widget by ID
$widget = isset( $GLOBALS['wp_registered_widgets'][ $this->current_widget_id ] ) ? $GLOBALS['wp_registered_widgets'][ $this->current_widget_id ] : false;
if ( $sidebar && $widget && isset( $widget['callback'] ) ) {
// prevent PHP notices by populating widget args
$widget_args = array(
'before_widget' => '',
'after_widget' => '',
'before_title' => '',
'after_title' => '',
);
// This is lamer - no API for outputting a given widget by ID
ob_start();
// Process the widget to populate Grunion_Contact_Form::$last
call_user_func( $widget['callback'], $widget_args, $widget['params'][0] );
ob_end_clean();
}
} else {
// It's a form embedded in a post
$post = get_post( $id );
// Process the content to populate Grunion_Contact_Form::$last
/** This filter is already documented in core. wp-includes/post-template.php */
apply_filters( 'the_content', $post->post_content );
}
$form = isset( Grunion_Contact_Form::$forms[ $hash ] ) ? Grunion_Contact_Form::$forms[ $hash ] : null;
// No form may mean user is using do_shortcode, grab the form using the stored post meta
if ( ! $form ) {
// Get shortcode from post meta
$shortcode = get_post_meta( $_POST['contact-form-id'], "_g_feedback_shortcode_{$hash}", true );
// Format it
if ( $shortcode != '' ) {
// Get attributes from post meta.
$parameters = '';
$attributes = get_post_meta( $_POST['contact-form-id'], "_g_feedback_shortcode_atts_{$hash}", true );
if ( ! empty( $attributes ) && is_array( $attributes ) ) {
foreach( array_filter( $attributes ) as $param => $value ) {
$parameters .= " $param=\"$value\"";
}
}
$shortcode = '[contact-form' . $parameters . ']' . $shortcode . '[/contact-form]';
do_shortcode( $shortcode );
// Recreate form
$form = Grunion_Contact_Form::$last;
}
if ( ! $form ) {
return false;
}
}
if ( is_wp_error( $form->errors ) && $form->errors->get_error_codes() ) {
return $form->errors;
}
// Process the form
return $form->process_submission();
}
function ajax_request() {
$submission_result = self::process_form_submission();
if ( ! $submission_result ) {
header( 'HTTP/1.1 500 Server Error', 500, true );
echo '<div class="form-error"><ul class="form-errors"><li class="form-error-message">';
esc_html_e( 'An error occurred. Please try again later.', 'jetpack' );
echo '</li></ul></div>';
} elseif ( is_wp_error( $submission_result ) ) {
header( 'HTTP/1.1 400 Bad Request', 403, true );
echo '<div class="form-error"><ul class="form-errors"><li class="form-error-message">';
echo esc_html( $submission_result->get_error_message() );
echo '</li></ul></div>';
} else {
echo '<h3>' . esc_html__( 'Message Sent', 'jetpack' ) . '</h3>' . $submission_result;
}
die;
}
/**
* Ensure the post author is always zero for contact-form feedbacks
* Attached to `wp_insert_post_data`
*
* @see Grunion_Contact_Form::process_submission()
*
* @param array $data the data to insert
* @param array $postarr the data sent to wp_insert_post()
* @return array The filtered $data to insert
*/
function insert_feedback_filter( $data, $postarr ) {
if ( $data['post_type'] == 'feedback' && $postarr['post_type'] == 'feedback' ) {
$data['post_author'] = 0;
}
return $data;
}
/*
* Adds our contact-form shortcode
* The "child" contact-field shortcode is enabled as needed by the contact-form shortcode handler
*/
function add_shortcode() {
add_shortcode( 'contact-form', array( 'Grunion_Contact_Form', 'parse' ) );
add_shortcode( 'contact-field', array( 'Grunion_Contact_Form', 'parse_contact_field' ) );
}
static function tokenize_label( $label ) {
return '{' . trim( preg_replace( '#^\d+_#', '', $label ) ) . '}';
}
static function sanitize_value( $value ) {
return preg_replace( '=((<CR>|<LF>|0x0A/%0A|0x0D/%0D|\\n|\\r)\S).*=i', null, $value );
}
/**
* Replaces tokens like {city} or {City} (case insensitive) with the value
* of an input field of that name
*
* @param string $subject
* @param array $field_values Array with field label => field value associations
*
* @return string The filtered $subject with the tokens replaced
*/
function replace_tokens_with_input( $subject, $field_values ) {
// Wrap labels into tokens (inside {})
$wrapped_labels = array_map( array( 'Grunion_Contact_Form_Plugin', 'tokenize_label' ), array_keys( $field_values ) );
// Sanitize all values
$sanitized_values = array_map( array( 'Grunion_Contact_Form_Plugin', 'sanitize_value' ), array_values( $field_values ) );
foreach ( $sanitized_values as $k => $sanitized_value ) {
if ( is_array( $sanitized_value ) ) {
$sanitized_values[ $k ] = implode( ', ', $sanitized_value );
}
}
// Search for all valid tokens (based on existing fields) and replace with the field's value
$subject = str_ireplace( $wrapped_labels, $sanitized_values, $subject );
return $subject;
}
/**
* Tracks the widget currently being processed.
* Attached to `dynamic_sidebar`
*
* @see $current_widget_id
*
* @param array $widget The widget data
*/
function track_current_widget( $widget ) {
$this->current_widget_id = $widget['id'];
}
/**
* Adds a "widget" attribute to every contact-form embedded in a text widget.
* Used to tell the difference between post-embedded contact-forms and widget-embedded contact-forms
* Attached to `widget_text`
*
* @param string $text The widget text
* @return string The filtered widget text
*/
function widget_atts( $text ) {
Grunion_Contact_Form::style( true );
return preg_replace( '/\[contact-form([^a-zA-Z_-])/', '[contact-form widget="' . $this->current_widget_id . '"\\1', $text );
}
/**
* For sites where text widgets are not processed for shortcodes, we add this hack to process just our shortcode
* Attached to `widget_text`
*
* @param string $text The widget text
* @return string The contact-form filtered widget text
*/
function widget_shortcode_hack( $text ) {
if ( ! preg_match( '/\[contact-form([^a-zA-Z_-])/', $text ) ) {
return $text;
}
$old = $GLOBALS['shortcode_tags'];
remove_all_shortcodes();
Grunion_Contact_Form_Plugin::$using_contact_form_field = true;
$this->add_shortcode();
$text = do_shortcode( $text );
Grunion_Contact_Form_Plugin::$using_contact_form_field = false;
$GLOBALS['shortcode_tags'] = $old;
return $text;
}
/**
* Populate an array with all values necessary to submit a NEW contact-form feedback to Akismet.
* Note that this includes the current user_ip etc, so this should only be called when accepting a new item via $_POST
*
* @param array $form Contact form feedback array
* @return array feedback array with additional data ready for submission to Akismet
*/
function prepare_for_akismet( $form ) {
$form['comment_type'] = 'contact_form';
$form['user_ip'] = $_SERVER['REMOTE_ADDR'];
$form['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
$form['referrer'] = $_SERVER['HTTP_REFERER'];
$form['blog'] = get_option( 'home' );
foreach ( $_SERVER as $key => $value ) {
if ( ! is_string( $value ) ) {
continue;
}
if ( in_array( $key, array( 'HTTP_COOKIE', 'HTTP_COOKIE2', 'HTTP_USER_AGENT', 'HTTP_REFERER' ) ) ) {
// We don't care about cookies, and the UA and Referrer were caught above.
continue;
} elseif ( in_array( $key, array( 'REMOTE_ADDR', 'REQUEST_URI', 'DOCUMENT_URI' ) ) ) {
// All three of these are relevant indicators and should be passed along.
$form[ $key ] = $value;
} elseif ( wp_startswith( $key, 'HTTP_' ) ) {
// Any other HTTP header indicators.
// `wp_startswith()` is a wpcom helper function and is included in Jetpack via `functions.compat.php`
$form[ $key ] = $value;
}
}
return $form;
}
/**
* Submit contact-form data to Akismet to check for spam.
* If you're accepting a new item via $_POST, run it Grunion_Contact_Form_Plugin::prepare_for_akismet() first
* Attached to `jetpack_contact_form_is_spam`
*
* @param bool $is_spam
* @param array $form
* @return bool|WP_Error TRUE => spam, FALSE => not spam, WP_Error => stop processing entirely
*/
function is_spam_akismet( $is_spam, $form = array() ) {
global $akismet_api_host, $akismet_api_port;
// The signature of this function changed from accepting just $form.
// If something only sends an array, assume it's still using the old
// signature and work around it.
if ( empty( $form ) && is_array( $is_spam ) ) {
$form = $is_spam;
$is_spam = false;
}
// If a previous filter has alrady marked this as spam, trust that and move on.
if ( $is_spam ) {
return $is_spam;
}
if ( ! function_exists( 'akismet_http_post' ) && ! defined( 'AKISMET_VERSION' ) ) {
return false;
}
$query_string = http_build_query( $form );
if ( method_exists( 'Akismet', 'http_post' ) ) {
$response = Akismet::http_post( $query_string, 'comment-check' );
} else {
$response = akismet_http_post( $query_string, $akismet_api_host, '/1.1/comment-check', $akismet_api_port );
}
$result = false;
if ( isset( $response[0]['x-akismet-pro-tip'] ) && 'discard' === trim( $response[0]['x-akismet-pro-tip'] ) && get_option( 'akismet_strictness' ) === '1' ) {
$result = new WP_Error( 'feedback-discarded', __( 'Feedback discarded.', 'jetpack' ) );
} elseif ( isset( $response[1] ) && 'true' == trim( $response[1] ) ) { // 'true' is spam
$result = true;
}
/**
* Filter the results returned by Akismet for each submitted contact form.
*
* @module contact-form
*
* @since 1.3.1
*
* @param WP_Error|bool $result Is the submitted feedback spam.
* @param array|bool $form Submitted feedback.
*/
return apply_filters( 'contact_form_is_spam_akismet', $result, $form );
}
/**
* Submit a feedback as either spam or ham
*
* @param string $as Either 'spam' or 'ham'.
* @param array $form the contact-form data
*/
function akismet_submit( $as, $form ) {
global $akismet_api_host, $akismet_api_port;
if ( ! in_array( $as, array( 'ham', 'spam' ) ) ) {
return false;
}
$query_string = '';
if ( is_array( $form ) ) {
$query_string = http_build_query( $form );
}
if ( method_exists( 'Akismet', 'http_post' ) ) {
$response = Akismet::http_post( $query_string, "submit-{$as}" );
} else {
$response = akismet_http_post( $query_string, $akismet_api_host, "/1.1/submit-{$as}", $akismet_api_port );
}
return trim( $response[1] );
}
/**
* Prints the menu
*/
function export_form() {
$current_screen = get_current_screen();
if ( ! in_array( $current_screen->id, array( 'edit-feedback', 'feedback_page_feedback-export' ) ) ) {
return;
}
if ( ! current_user_can( 'export' ) ) {
return;
}
// if there aren't any feedbacks, bail out
if ( ! (int) wp_count_posts( 'feedback' )->publish ) {
return;
}
?>
<div id="feedback-export" style="display:none">
<h2><?php _e( 'Export feedback as CSV', 'jetpack' ) ?></h2>
<div class="clear"></div>
<form action="<?php echo admin_url( 'admin-post.php' ); ?>" method="post" class="form">
<?php wp_nonce_field( 'feedback_export','feedback_export_nonce' ); ?>
<input name="action" value="feedback_export" type="hidden">
<label for="post"><?php _e( 'Select feedback to download', 'jetpack' ) ?></label>
<select name="post">
<option value="all"><?php esc_html_e( 'All posts', 'jetpack' ) ?></option>
<?php echo $this->get_feedbacks_as_options() ?>
</select>
<br><br>
<input type="submit" name="submit" id="submit" class="button button-primary" value="<?php esc_html_e( 'Download', 'jetpack' ); ?>">
</form>
</div>
<?php
// There aren't any usable actions in core to output the "export feedback" form in the correct place,
// so this inline JS moves it from the top of the page to the bottom.
?>
<script type='text/javascript'>
var menu = document.getElementById( 'feedback-export' ),
wrapper = document.getElementsByClassName( 'wrap' )[0];
<?php if ( 'edit-feedback' === $current_screen->id ) : ?>
wrapper.appendChild(menu);
<?php endif; ?>
menu.style.display = 'block';
</script>
<?php
}
/**
* Fetch post content for a post and extract just the comment.
*
* @param int $post_id The post id to fetch the content for.
*
* @return string Trimmed post comment.
*
* @codeCoverageIgnore
*/
public function get_post_content_for_csv_export( $post_id ) {
$post_content = get_post_field( 'post_content', $post_id );
$content = explode( '<!--more-->', $post_content );
return trim( $content[0] );
}
/**
* Get `_feedback_extra_fields` field from post meta data.
*
* @param int $post_id Id of the post to fetch meta data for.
*
* @return mixed
*
* @codeCoverageIgnore - No need to be covered.
*/
public function get_post_meta_for_csv_export( $post_id ) {
return get_post_meta( $post_id, '_feedback_extra_fields', true );
}
/**
* Get parsed feedback post fields.
*
* @param int $post_id Id of the post to fetch parsed contents for.
*
* @return array
*
* @codeCoverageIgnore - No need to be covered.
*/
public function get_parsed_field_contents_of_post( $post_id ) {
return self::parse_fields_from_content( $post_id );
}
/**
* Properly maps fields that are missing from the post meta data
* to names, that are similar to those of the post meta.
*
* @param array $parsed_post_content Parsed post content
*
* @see parse_fields_from_content for how the input data is generated.
*
* @return array Mapped fields.
*/
public function map_parsed_field_contents_of_post_to_field_names( $parsed_post_content ) {
$mapped_fields = array();
$field_mapping = array(
'_feedback_subject' => __( 'Contact Form', 'jetpack' ),
'_feedback_author' => '1_Name',
'_feedback_author_email' => '2_Email',
'_feedback_author_url' => '3_Website',
'_feedback_main_comment' => '4_Comment',
);
foreach ( $field_mapping as $parsed_field_name => $field_name ) {
if (
isset( $parsed_post_content[ $parsed_field_name ] )
&& ! empty( $parsed_post_content[ $parsed_field_name ] )
) {
$mapped_fields[ $field_name ] = $parsed_post_content[ $parsed_field_name ];
}
}
return $mapped_fields;
}
/**
* Prepares feedback post data for CSV export.
*
* @param array $post_ids Post IDs to fetch the data for. These need to be Feedback posts.
*
* @return array
*/
public function get_export_data_for_posts( $post_ids ) {
$posts_data = array();
$field_names = array();
$result = array();
/**
* Fetch posts and get the possible field names for later use
*/
foreach ( $post_ids as $post_id ) {
/**
* Fetch post main data, because we need the subject and author data for the feedback form.
*/
$post_real_data = $this->get_parsed_field_contents_of_post( $post_id );
/**
* If `$post_real_data` is not an array or there is no `_feedback_subject` set,
* then something must be wrong with the feedback post. Skip it.
*/
if ( ! is_array( $post_real_data ) || ! isset( $post_real_data['_feedback_subject'] ) ) {
continue;
}
/**
* Fetch main post comment. This is from the default textarea fields.
* If it is non-empty, then we add it to data, otherwise skip it.
*/
$post_comment_content = $this->get_post_content_for_csv_export( $post_id );
if ( ! empty( $post_comment_content ) ) {
$post_real_data['_feedback_main_comment'] = $post_comment_content;
}
/**
* Map parsed fields to proper field names
*/
$mapped_fields = $this->map_parsed_field_contents_of_post_to_field_names( $post_real_data );
/**
* Fetch post meta data.
*/
$post_meta_data = $this->get_post_meta_for_csv_export( $post_id );
/**
* If `$post_meta_data` is not an array or if it is empty, then there is no
* extra feedback to work with. Create an empty array.
*/
if ( ! is_array( $post_meta_data ) || empty( $post_meta_data ) ) {
$post_meta_data = array();
}
/**
* Prepend the feedback subject to the list of fields.
*/
$post_meta_data = array_merge(
$mapped_fields,
$post_meta_data
);
/**
* Save post metadata for later usage.
*/
$posts_data[ $post_id ] = $post_meta_data;
/**
* Save field names, so we can use them as header fields later in the CSV.
*/
$field_names = array_merge( $field_names, array_keys( $post_meta_data ) );
}
/**
* Make sure the field names are unique, because we don't want duplicate data.
*/
$field_names = array_unique( $field_names );
/**
* Sort the field names by the field id number
*/
sort( $field_names, SORT_NUMERIC );
/**
* Loop through every post, which is essentially CSV row.
*/
foreach ( $posts_data as $post_id => $single_post_data ) {
/**
* Go through all the possible fields and check if the field is available
* in the current post.
*
* If it is - add the data as a value.
* If it is not - add an empty string, which is just a placeholder in the CSV.
*/
foreach ( $field_names as $single_field_name ) {
if (
isset( $single_post_data[ $single_field_name ] )
&& ! empty( $single_post_data[ $single_field_name ] )
) {
$result[ $single_field_name ][] = trim( $single_post_data[ $single_field_name ] );
} else {
$result[ $single_field_name ][] = '';
}
}
}
return $result;
}
/**
* download as a csv a contact form or all of them in a csv file
*/
function download_feedback_as_csv() {
if ( empty( $_POST['feedback_export_nonce'] ) ) {
return;
}
check_admin_referer( 'feedback_export', 'feedback_export_nonce' );
if ( ! current_user_can( 'export' ) ) {
return;
}
$args = array(
'posts_per_page' => -1,
'post_type' => 'feedback',
'post_status' => 'publish',
'order' => 'ASC',
'fields' => 'ids',
'suppress_filters' => false,
);
$filename = date( 'Y-m-d' ) . '-feedback-export.csv';
// Check if we want to download all the feedbacks or just a certain contact form
if ( ! empty( $_POST['post'] ) && $_POST['post'] !== 'all' ) {
$args['post_parent'] = (int) $_POST['post'];
$filename = date( 'Y-m-d' ) . '-' . str_replace( ' ', '-', get_the_title( (int) $_POST['post'] ) ) . '.csv';
}
$feedbacks = get_posts( $args );
if ( empty( $feedbacks ) ) {
return;
}
$filename = sanitize_file_name( $filename );
/**
* Prepare data for export.
*/
$data = $this->get_export_data_for_posts( $feedbacks );
/**
* If `$data` is empty, there's nothing we can do below.
*/
if ( ! is_array( $data ) || empty( $data ) ) {
return;
}
/**
* Extract field names from `$data` for later use.
*/
$fields = array_keys( $data );
/**
* Count how many rows will be exported.
*/
$row_count = count( reset( $data ) );
// Forces the download of the CSV instead of echoing
header( 'Content-Disposition: attachment; filename=' . $filename );
header( 'Pragma: no-cache' );
header( 'Expires: 0' );
header( 'Content-Type: text/csv; charset=utf-8' );
$output = fopen( 'php://output', 'w' );
/**
* Print CSV headers
*/
fputcsv( $output, $fields );
/**
* Print rows to the output.
*/
for ( $i = 0; $i < $row_count; $i ++ ) {
$current_row = array();
/**
* Put all the fields in `$current_row` array.
*/
foreach ( $fields as $single_field_name ) {
$current_row[] = $this->esc_csv( $data[ $single_field_name ][ $i ] );
}
/**
* Output the complete CSV row
*/
fputcsv( $output, $current_row );
}
fclose( $output );
}
/**
* Escape a string to be used in a CSV context
*
* Malicious input can inject formulas into CSV files, opening up the possibility for phishing attacks and
* disclosure of sensitive information.
*
* Additionally, Excel exposes the ability to launch arbitrary commands through the DDE protocol.
*
* @see http://www.contextis.com/resources/blog/comma-separated-vulnerabilities/
*
* @param string $field
*
* @return string
*/
public function esc_csv( $field ) {
$active_content_triggers = array( '=', '+', '-', '@' );
if ( in_array( mb_substr( $field, 0, 1 ), $active_content_triggers, true ) ) {
$field = "'" . $field;
}
return $field;
}
/**
* Returns a string of HTML <option> items from an array of posts
*
* @return string a string of HTML <option> items
*/
protected function get_feedbacks_as_options() {
$options = '';
// Get the feedbacks' parents' post IDs
$feedbacks = get_posts( array(
'fields' => 'id=>parent',
'posts_per_page' => 100000,
'post_type' => 'feedback',
'post_status' => 'publish',
'suppress_filters' => false,
) );
$parents = array_unique( array_values( $feedbacks ) );
$posts = get_posts( array(
'orderby' => 'ID',
'posts_per_page' => 1000,
'post_type' => 'any',
'post__in' => array_values( $parents ),
'suppress_filters' => false,
) );
// creates the string of <option> elements
foreach ( $posts as $post ) {
$options .= sprintf( '<option value="%s">%s</option>', esc_attr( $post->ID ), esc_html( $post->post_title ) );
}
return $options;
}
/**
* Get the names of all the form's fields
*
* @param array|int $posts the post we want the fields of
*
* @return array the array of fields
*
* @deprecated As this is no longer necessary as of the CSV export rewrite. - 2015-12-29
*/
protected function get_field_names( $posts ) {
$posts = (array) $posts;
$all_fields = array();
foreach ( $posts as $post ) {