-
Notifications
You must be signed in to change notification settings - Fork 7
/
class-gf-polls.php
2455 lines (2037 loc) · 86.2 KB
/
class-gf-polls.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
// example usage of gpoll_widget_override filter to allow widgets to override form settings
/*
add_filter('gpoll_widget_override' , 'gpoll_widget_override');
function gpoll_widget_override($form_ids){
array_push($form_ids, 7, 9);
return $form_ids;
}
*/
// The wp_cron job will take over the calculation of the results if 5 seconds is not long enough at the time of form submission/update.
// The default schedule is set to hourly to avoid heavy loads on the server but you can change this frequency by using the gform_polls_cron_schedule.
// The format follows the format required by the WordPress cron_schedules filter. http://codex.wordpress.org/Function_Reference/wp_get_schedules
// Important: the Polls Add-On must be deactivated and reactivated in order to reschedule the task.
/*
add_filter( 'gform_polls_cron_schedule', 'gform_polls_cron_add_twice_hourly' );
function gform_polls_cron_add_twice_hourly($schedules) {
// Adds twice hourly to the existing schedules.
$schedules['twicehourly'] = array(
'interval' => 1800, // number of seconds in the interval
'display' => 'Twice Hourly'
);
return $schedules;
}
*/
// By default the percentage will round to the nearest whole number
// This can be overridden with the gform_polls_percentage_precision hook
/*
add_filter('gform_polls_percentage_precision', 'gform_polls_custom_precision', 10, 2);
function gform_polls_custom_precision($precision, $form_id){
return 1;
}
*/
//------------------------------------------
defined( 'ABSPATH' ) || die();
GFForms::include_addon_framework();
require_once( 'pollwidget.php' );
register_deactivation_hook( __FILE__, array( 'GFPolls', 'remove_wp_cron_task' ) );
class GFPolls extends GFAddOn {
private static $_instance = null;
public $_version = GF_POLLS_VERSION;
protected $_min_gravityforms_version = '1.9.15.12';
protected $_slug = 'gravityformspolls';
protected $_path = 'gravityformspolls/polls.php';
protected $_full_path = __FILE__;
protected $_url = 'http://www.gravityforms.com';
protected $_title = 'Gravity Forms Polls Add-On';
protected $_short_title = 'Polls';
protected $_enable_rg_autoupgrade = true;
private $_form_meta_by_id = array();
public $gpoll_add_scripts;
/**
* Members plugin integration
*/
protected $_capabilities = array(
'gravityforms_polls',
'gravityforms_polls_uninstall',
'gravityforms_polls_results',
'gravityforms_polls_settings',
'gravityforms_polls_form_settings'
);
/**
* Permissions
*/
protected $_capabilities_settings_page = 'gravityforms_polls_settings';
protected $_capabilities_form_settings = 'gravityforms_polls_form_settings';
protected $_capabilities_uninstall = 'gravityforms_polls_uninstall';
/**
* Get an instance of this class.
*
* @return GFPolls
*/
public static function get_instance() {
if ( self::$_instance == null ) {
self::$_instance = new GFPolls();
}
return self::$_instance;
}
private function __clone() {
} /* do nothing */
/**
* Handles anything which requires early initialization.
*/
public function pre_init() {
parent::pre_init();
if ( $this->is_gravityforms_supported() && class_exists( 'GF_Field' ) ) {
require_once( 'includes/class-gf-field-poll.php' );
add_action( 'gform_after_submission', array( $this, 'after_submission' ), 10, 2 );
add_filter( 'gform_export_field_value', array( $this, 'display_entries_field_value' ), 10, 4 );
add_action( 'gform_polls_cron', array( $this, 'wp_cron_task' ) );
}
}
/**
* Handles hooks and loading of language files.
*
* @since 3.3 Register Polls block.
*/
public function init() {
// add a special class to poll fields so we can identify them later
add_action( 'gform_field_css_class', array( $this, 'add_custom_class' ), 10, 3 );
if ( $this->get_custom_cron_schedule() ) {
add_filter( 'cron_schedules', array( $this, 'cron_add_custom_schedule' ) );
}
// add wp_cron job if it's not already scheduled
if ( ! wp_next_scheduled( 'gform_polls_cron' ) ) {
wp_schedule_event( time(), $this->get_cron_recurrence(), 'gform_polls_cron' );
}
add_filter( 'gform_shortcode_polls', array( $this, 'poll_shortcode' ), 10, 3 );
add_filter( 'gform_pre_render', array( $this, 'pre_render' ) );
// shuffle choices if configured
add_filter( 'gform_field_content', array( $this, 'render_poll_field_content' ), 10, 5 );
add_action( 'gform_validation', array( $this, 'form_validation' ) );
// update the cache
add_action( 'gform_entry_created', array( $this, 'entry_created' ), 10, 2 );
// maybe display results on confirmation
add_filter( 'gform_confirmation', array( $this, 'display_confirmation' ), 10, 4 );
add_shortcode( 'gfpolls_total', array( $this, 'poll_total_shortcode' ) );
// merge tags
add_filter( 'gform_replace_merge_tags', array( $this, 'render_merge_tag' ), 10, 7 );
add_filter( 'gform_entry_field_value', array( $this, 'display_poll_on_entry_detail' ), 10, 4 );
// Integration with the feed add-ons as of GF 1.9.15.12; for add-ons which don't override get_field_value().
add_filter( 'gform_addon_field_value', array( $this, 'addon_field_value' ), 10, 5 );
// AWeber 2.3 and newer use the gform_addon_field_value hook, only use the gform_aweber_field_value hook with older versions.
if ( defined( 'GF_AWEBER_VERSION' ) && version_compare( GF_AWEBER_VERSION, '2.3', '<' ) ) {
add_filter( 'gform_aweber_field_value', array( $this, 'display_entries_field_value' ), 10, 4 );
}
// Mailchimp Add-On integration
add_filter( 'gform_mailchimp_field_value', array( $this, 'display_entries_field_value' ), 10, 4 );
// Campaign Monitor Add-On integration
add_filter( 'gform_campaignmonitor_field_value', array( $this, 'display_entries_field_value' ), 10, 4 );
// Zapier Add-On integration
add_filter( 'gform_zapier_field_value', array( $this, 'display_entries_field_value' ), 10, 4 );
// Register Polls block.
if ( class_exists( 'GF_Blocks' ) ) {
require_once( $this->get_base_path() . '/includes/class-gf-block-polls.php' );
}
parent::init();
}
/**
* Initialize the admin specific hooks.
*/
public function init_admin() {
//form editor
add_action( 'gform_field_standard_settings', array( $this, 'poll_field_settings' ), 10, 2 );
add_filter( 'gform_tooltips', array( $this, 'add_poll_field_tooltips' ) );
add_action( 'gform_after_save_form', array( $this, 'after_save_form' ), 10, 2 );
//display poll results on entry list
add_filter( 'gform_entries_field_value', array( $this, 'display_entries_field_value' ), 10, 4 );
//merge tags
add_filter( 'gform_admin_pre_render', array( $this, 'add_merge_tags' ) );
//update the cache
add_action( 'gform_after_update_entry', array( $this, 'entry_updated' ), 10, 2 );
add_action( 'gform_update_status', array( $this, 'update_entry_status' ), 10, 2 );
// contacts
add_filter( 'gform_contacts_tabs_contact_detail', array( $this, 'add_tab_to_contact_detail' ), 10, 2 );
add_action( 'gform_contacts_tab_polls', array( $this, 'contacts_tab' ) );
// Adds the polls action to the shortcode builder UI
add_filter( 'gform_shortcode_builder_actions', array( $this, 'add_polls_shortcode_ui_action' ) );
parent::init_admin();
}
/**
* Initialize the AJAX hooks.
*/
public function init_ajax() {
add_action( 'wp_ajax_gpoll_ajax', array( $this, 'gpoll_ajax' ) );
add_action( 'wp_ajax_nopriv_gpoll_ajax', array( $this, 'gpoll_ajax' ) );
parent::init_ajax();
}
/**
* The Polls add-on does not support logging.
*
* @param array $plugins The plugins which support logging.
*
* @return array
*/
public function set_logging_supported( $plugins ) {
return $plugins;
}
// # SCRIPTS & STYLES -----------------------------------------------------------------------------------------------
/**
* Return the scripts which should be enqueued.
*
* @return array
*/
public function scripts() {
$min = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG || isset( $_GET['gform_debug'] ) ? '' : '.min';
$scripts = array(
array(
'handle' => 'gpoll_form_editor_js',
'src' => $this->get_base_url() . "/js/gpoll_form_editor{$min}.js",
'version' => $this->_version,
'deps' => array( 'jquery' ),
'strings' => array(
'firstChoice' => wp_strip_all_tags( __( 'First Choice', 'gravityformspolls' ) ),
'secondChoice' => wp_strip_all_tags( __( 'Second Choice', 'gravityformspolls' ) ),
'thirdChoice' => wp_strip_all_tags( __( 'Third Choice', 'gravityformspolls' ) )
),
'enqueue' => array(
array( 'admin_page' => array( 'form_editor' ) ),
)
),
array(
'handle' => 'gpoll_form_settings_js',
'src' => $this->get_base_url() . "/js/gpoll_form_settings{$min}.js",
'version' => $this->_version,
'deps' => array( 'jquery' ),
'enqueue' => array(
array(
'admin_page' => array( 'form_settings' ),
'tab' => 'gravityformspolls',
),
)
),
array(
'handle' => 'gpoll_js',
'src' => $this->get_base_url() . "/js/gpoll{$min}.js",
'version' => $this->_version,
'deps' => array( 'jquery' ),
'callback' => array( $this, 'localize_scripts' ),
'enqueue' => array(
array( 'field_types' => array( 'poll' ) ),
)
),
);
return array_merge( parent::scripts(), $scripts );
}
/**
* Return the stylesheets which should be enqueued.
*
* @return array
*/
public function styles() {
$min = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG || isset( $_GET['gform_debug'] ) ? '' : '.min';
$styles = array(
array(
'handle' => 'gpoll_form_editor_css',
'src' => $this->get_base_url() . "/css/gpoll_form_editor{$min}.css",
'version' => $this->_version,
'enqueue' => array(
array( 'admin_page' => array( 'form_editor' ) ),
)
),
array(
'handle' => 'gpoll_css',
'src' => $this->get_base_url() . "/css/gpoll{$min}.css",
'version' => $this->_version,
'enqueue' => array(
array( 'field_types' => array( 'poll' ) ),
array( 'admin_page' => array( 'form_editor', 'results', 'entry_view', 'entry_detail' ) ),
)
),
);
return array_merge( parent::styles(), $styles );
}
/**
* Localize the strings used by the scripts.
*/
public function localize_scripts() {
// Get current page protocol
$protocol = isset( $_SERVER['HTTPS'] ) ? 'https://' : 'http://';
// Output admin-ajax.php URL with same protocol as current page
$params = array(
'ajaxurl' => admin_url( 'admin-ajax.php', $protocol ),
'imagesUrl' => $this->get_base_url() . '/images'
);
wp_localize_script( 'gpoll_js', 'gpollVars', $params );
//localisable strings for the js file
$strings = array(
'viewResults' => esc_html__( 'View results', 'gravityformspolls' ),
'backToThePoll' => esc_html__( 'Back to the poll', 'gravityformspolls' )
);
wp_localize_script( 'gpoll_js', 'gpoll_strings', $strings );
}
// # RESULTS --------------------------------------------------------------------------------------------------------
/**
* Configure the survey results page.
*
* @return array
*/
public function get_results_page_config() {
return array(
'title' => esc_html__( 'Poll Results', 'gravityformspolls' ),
'capabilities' => array( 'gravityforms_polls_results' ),
'callbacks' => array(
'fields' => array( $this, 'results_fields' )
)
);
}
/**
* Get all the poll fields for the current form.
*
* @param array $form The current form object.
*
* @return GF_Field[]
*/
public function results_fields( $form ) {
return GFAPI::get_fields_by_type( $form, array( 'poll' ) );
}
// # MERGE TAGS -----------------------------------------------------------------------------------------------------
/**
* Add the result merge tags to the merge tag drop downs in the admin.
*
* @param array $form The current form.
*
* @return array
*/
public function add_merge_tags( $form ) {
if ( ! $this->is_form_settings() ) {
return $form;
}
$poll_fields = GFAPI::get_fields_by_type( $form, array( 'poll' ) );
if ( empty( $poll_fields ) ) {
return $form;
}
foreach ( $poll_fields as $field ) {
$field_id = $field->id;
$field_label = $field->label;
$group = $field->isRequired ? 'required' : 'optional';
$merge_tags[] = array(
'group' => $group,
'label' => $field_label . esc_html__( ': Poll Results', 'gravityformspolls' ),
'tag' => "{gpoll:field={$field_id}}"
);
}
$merge_tags[] = array( 'group' => 'other', 'label' => esc_html__( 'All Poll Results', 'gravityformspolls' ), 'tag' => '{all_poll_results}' );
?>
<script type="text/javascript">
if (window.gform)
gform.addFilter("gform_merge_tags", "gpoll_add_merge_tags");
function gpoll_add_merge_tags(mergeTags, elementId, hideAllFields, excludeFieldTypes, isPrepop, option) {
if (isPrepop)
return mergeTags;
var customMergeTags = <?php echo json_encode( $merge_tags ); ?>;
jQuery.each(customMergeTags, function (i, customMergeTag) {
mergeTags[customMergeTag.group].tags.push({tag: customMergeTag.tag, label: customMergeTag.label});
});
return mergeTags;
}
</script>
<?php
//return the form object from the php hook
return $form;
}
/**
* Replace the result merge tags.
*
* @param string $text The current text in which merge tags are being replaced.
* @param array $form The current form object.
* @param array $entry The current entry object.
* @param bool $url_encode Whether or not to encode any URLs found in the replaced value.
* @param bool $esc_html Whether or not to encode HTML found in the replaced value.
* @param bool $nl2br Whether or not to convert newlines to break tags.
* @param string $format The format requested for the location the merge is being used. Possible values: html, text or url.
*
* @return string
*/
public function render_merge_tag( $text, $form, $entry, $url_encode, $esc_html, $nl2br, $format ) {
if ( empty( $entry ) || empty( $form ) ) {
return $text;
}
$poll_fields = GFAPI::get_fields_by_type( $form, array( 'poll' ) );
if ( empty ( $poll_fields ) ) {
return $text;
}
$enqueue_scripts = false;
$form_id = $form['id'];
preg_match_all( "/{all_poll_results(:(.*?))?}/", $text, $matches, PREG_SET_ORDER );
foreach ( $matches as $match ) {
$full_tag = $match[0];
$options_string = isset( $match[2] ) ? $match[2] : '';
$options = shortcode_parse_atts( $options_string );
extract(
shortcode_atts(
array(
'field' => 0,
'style' => 'green',
'percentages' => 'true',
'counts' => 'true',
), $options
)
);
$percentages = strtolower( $percentages ) == 'false' ? false : true;
$counts = strtolower( $counts ) == 'false' ? false : true;
$results = $this->gpoll_get_results( $form_id, $field, $style, $percentages, $counts, $entry );
$results_summary = $results['summary'];
$new_value = $results_summary;
$text = str_replace( $full_tag, $new_value, $text );
$enqueue_scripts = true;
}
preg_match_all( "/\{gpoll:(.*?)\}/", $text, $matches, PREG_SET_ORDER );
foreach ( $matches as $match ) {
$full_tag = $match[0];
$options_string = isset( $match[1] ) ? $match[1] : '';
$options = shortcode_parse_atts( $options_string );
extract(
shortcode_atts(
array(
'field' => 0,
'style' => 'green',
'percentages' => 'true',
'counts' => 'true',
), $options
)
);
$percentages = strtolower( $percentages ) == 'false' ? false : true;
$counts = strtolower( $counts ) == 'false' ? false : true;
$results = $this->gpoll_get_results( $form_id, $field, $style, $percentages, $counts, $entry );
$results_summary = $results['summary'];
$new_value = $results_summary;
$text = str_replace( $full_tag, $new_value, $text );
$enqueue_scripts = true;
}
if ( $enqueue_scripts ) {
wp_enqueue_script( 'jquery' );
wp_enqueue_style( 'gpoll_css' );
wp_enqueue_style( 'gpoll_form_editor_css' );
wp_enqueue_script( 'gpoll_js' );
$this->localize_scripts();
}
return $text;
}
// # FORM RENDER & SUBMISSION ---------------------------------------------------------------------------------------
/**
* Helper for retrieving a form setting.
*
* @param array $form The current form object.
* @param string $setting_name The property to be retrieved.
*
* @return bool|string
*/
public function get_form_setting( $form, $setting_name ) {
if ( false === empty( $form ) ) {
$settings = $this->get_form_settings( $form );
// check for legacy form settings from a form exported from a previous version pre-framework
if ( empty( $settings ) && isset( $form['gpollDisplayResults'] ) ) {
$this->upgrade_form_settings( $form );
}
if ( isset( $settings[ $setting_name ] ) ) {
$setting_value = $settings[ $setting_name ];
if ( $setting_value == '1' ) {
$setting_value = true;
} elseif ( $setting_value == '0' ) {
$setting_value = false;
}
return $setting_value;
}
}
$setting_value = '';
//default values
switch ( $setting_name ) {
case 'displayResults' :
case 'showResultsLink' :
case 'showPercentages' :
case 'showCounts' :
$setting_value = true;
break;
case 'blockRepeatVoters' :
$setting_value = false;
break;
case 'style' :
$setting_value = 'green';
break;
case 'cookie' :
$setting_value = '1 month';
break;
}
return $setting_value;
}
/**
* Updates the form object with the appropriate css classes and if necessary configures the select placeholder.
*
* @param array $form The for currently being processed for display.
*
* @return array
*/
public function pre_render( $form ) {
$poll_fields = GFAPI::get_fields_by_type( $form, array( 'poll' ) );
if ( ! empty ( $poll_fields ) ) {
$form_css = 'gpoll_enabled';
$show_results_link = $this->get_form_setting( $form, 'showResultsLink' );
if ( $show_results_link ) {
$form_css .= ' gpoll_show_results_link';
}
$block_repeat_voters = $this->get_form_setting( $form, 'blockRepeatVoters' );
if ( $block_repeat_voters && rgget( 'gf_page' ) != 'preview' ) {
$form_css .= ' gpoll_block_repeat_voters';
}
$form['cssClass'] = empty( $form['cssClass'] ) ? $form_css . ' gpoll' : $form_css . ' ' . $form['cssClass'];
foreach ( $form['fields'] as &$field ) {
if ( $field->type != 'poll' ) {
continue;
}
if ( $field->get_input_type() == 'select' && empty( $field->placeholder ) ) {
$field->placeholder = esc_html__( 'Select one', 'gravityformspolls' );
}
}
}
return $form;
}
/**
* If necessary perform validation to prevent repeat voting.
*
* @param array $validation_result Contains the validation result, the form object, and the failed validation page number.
*
* @return array
*/
public function form_validation( $validation_result ) {
$form = $validation_result['form'];
$poll_fields = GFAPI::get_fields_by_type( $form, array( 'poll' ) );
if ( empty ( $poll_fields ) ) {
return $validation_result;
}
$form_setting_block_repeat = $this->get_form_setting( $form, 'blockRepeatVoters' );
$field_values = wp_parse_args( rgpost( 'gform_field_values' ) );
if ( $form_setting_block_repeat || ( isset( $field_values['gpoll_enabled'] ) && $field_values['gpoll_enabled'] == '1' && isset( $field_values['gpoll_cookie'] ) && false === empty( $field_values['gpoll_cookie'] ) ) ) {
$form_id = rgar( $form, 'id' );
if ( isset ( $_COOKIE[ 'gpoll_form_' . $form_id ] ) ) {
// set the form validation to false
$validation_result['is_valid'] = false;
foreach ( $form['fields'] as &$field ) {
if ( $field->type == 'poll' ) {
$field->failed_validation = true;
$field->validation_message = esc_html__( 'Repeat voting is not allowed', 'gravityformspolls' );
}
}
$validation_result['form'] = $form;
}
}
return $validation_result;
}
/**
* If necessary randomize the field choices.
*
* @param string $content The field content to be filtered.
* @param GF_Field $field The field currently being processed for display.
* @param string|array $value The field value. From default/dynamic population, $_POST, or a resumed incomplete submission.
* @param int $entry_id The ID of the entry if the field is being displayed on the entry detail page.
* @param int $form_id The ID of the current form.
*
* @return string
*/
public function render_poll_field_content( $content, $field, $value, $entry_id, $form_id ) {
if ( $entry_id === 0 && $field->type == 'poll' && ! $this->is_form_editor() ) {
if ( $field->enableRandomizeChoices ) {
//pass the HTML for the choices through DOMdocument to make sure we get the complete node.
$dom = new DOMDocument();
$content = '<?xml version="1.0" encoding="UTF-8"?>' . $content;
// Clean content from new line characters.
$content = str_replace(' ', ' ' ,$content);
$content = trim(preg_replace('/\s\s+/', ' ', $content));
$loader = libxml_disable_entity_loader( true );
$errors = libxml_use_internal_errors( true );
$dom->loadHTML( $content );
libxml_clear_errors();
libxml_use_internal_errors( $errors );
libxml_disable_entity_loader( $loader );
$content = $dom->saveXML( $dom->documentElement );
$options_container_tag = 'div';
$legacy_markup = method_exists( 'GFCommon', 'is_legacy_markup_enabled') ? GFCommon::is_legacy_markup_enabled( $form_id ) : true ;
if( $legacy_markup ){
$options_container_tag = 'ul';
}
//pick out the elements: div or (legacy ul) for radio & checkbox, OPTION for select.
$element_name = $field->inputType == 'select' ? 'select' : $options_container_tag;
if( $element_name == 'div' ){
// Options container is within the field div container,
// so we need to go two levels deep if we are looking by 'div' tag.
$nodes = $dom->getElementsByTagName( $element_name )->item( 0 )->childNodes->item(0)->childNodes;
} else {
$nodes = $dom->getElementsByTagName( $element_name )->item( 0 )->childNodes;
}
//cycle through the answers elements and swap them around randomly
$temp_str1 = 'gpoll_shuffle_placeholder1';
$temp_str2 = 'gpoll_shuffle_placeholder2';
for ( $i = $nodes->length - 1; $i >= 0; $i -- ) {
$n = rand( 0, $i );
if ( $i <> $n ) {
$i_str = $dom->saveXML( $nodes->item( $i ) );
$n_str = $dom->saveXML( $nodes->item( $n ) );
// Make sure we are not shuffling any of the following :
// select all option for checkboxes, select one placeholder for dropdown or other for radio buttons.
$no_shuffle_strings = array( 'gchoice_select_all', 'gf_placeholder', 'gf_other_choice');
if( str_replace( $no_shuffle_strings, '', $i_str ) !== $i_str ||
str_replace( $no_shuffle_strings, '', $n_str ) !== $n_str ){
continue;
}
$content = str_replace( $i_str, $temp_str1, $content );
$content = str_replace( $n_str, $temp_str2, $content );
$content = str_replace( $temp_str2, $i_str, $content );
$content = str_replace( $temp_str1, $n_str, $content );
}
}
//snip off the tags that DOMdocument adds
$content = str_replace( '<html><body>', '', $content );
$content = str_replace( '</body></html>', '', $content );
}
}
return $content;
}
/**
* If necessary update the confirmation to include the results.
*
* @param string|array $confirmation The forms current confirmation.
* @param array $form The form currently being processed.
* @param array $lead The entry currently being processed.
* @param bool $ajax Indicates if AJAX is enabled for this form.
*
* @return string|array
*/
public function display_confirmation( $confirmation, $form, $lead, $ajax ) {
$poll_fields = GFAPI::get_fields_by_type( $form, array( 'poll' ) );
if ( empty ( $poll_fields ) ) {
return $confirmation;
}
$form_id = $form['id'];
$display_confirmation = false;
$display_results = false;
$override = false;
$field_values = array();
if ( isset( $_POST['gform_field_values'] ) ) {
$field_values = wp_parse_args( $_POST['gform_field_values'] );
}
// shortcode attributes override form settings
if ( rgar( $field_values, 'gpoll_enabled' ) == '1' ) {
$field_values = wp_parse_args( $_POST['gform_field_values'] );
$show_results_link = rgar( $field_values, 'gpoll_show_results_link' );
$show_results_link = $show_results_link == '1' ? true : false;
$style = rgar( $field_values, 'gpoll_style' );
$percentages = rgar( $field_values, 'gpoll_percentages' );
$percentages = $percentages == '1' ? true : false;
$counts = rgar( $field_values, 'gpoll_counts' );
$counts = $counts == '1' ? true : false;
$cookie = rgar( $field_values, 'gpoll_cookie' );
$display_results = rgar( $field_values, 'gpoll_display_results' );
$display_results = $display_results == '1' ? true : false;
$display_confirmation = rgar( $field_values, 'gpoll_confirmation' );
$display_confirmation = $display_confirmation == '1' ? true : false;
$checksum = rgar( $field_values, 'gpoll_checksum' );
if ( $checksum == $this->generate_checksum( $display_results, $show_results_link, $cookie, $display_confirmation, $percentages, $counts, $style ) ) {
$override = true;
}
}
if ( false === $override ) {
$style = $this->get_form_setting( $form, 'style' );
$percentages = $this->get_form_setting( $form, 'showPercentages' );
$counts = $this->get_form_setting( $form, 'showCounts' );
$display_results = $this->get_form_setting( $form, 'displayResults' );
$display_confirmation = true;
}
$submitted_fields = array();
foreach ( $poll_fields as $field ) {
$field_id = $field->id;
$entry_value = RGFormsModel::get_lead_field_value( $lead, $field );
if ( is_array( $entry_value ) ) {
$entry_value = implode( '', $entry_value );
}
if ( false === empty( $entry_value ) ) {
$submitted_fields[] = $field_id;
}
}
if ( $display_confirmation && $display_results ) {
//confirmation message plus results
//override in the case of headers already sent or ajax = true
if ( is_array( $confirmation ) && array_key_exists( 'redirect', $confirmation ) ) {
$confirmation = '';
}
//override confirmation if it's a redirect
$str_pos = strpos( $confirmation, 'gformRedirect' );
if ( false !== $str_pos ) {
$confirmation = '';
}
$has_confirmation_wrapper = false !== strpos( $confirmation, 'gform_confirmation_wrapper' ) ? true : false;
if ( $has_confirmation_wrapper ) {
$confirmation = substr( $confirmation, 0, strlen( $confirmation ) - 6 );
} //remove the closing div of the wrapper
$has_confirmation_message = false !== strpos( $confirmation, 'gform_confirmation_message' ) ? true : false;
if ( $has_confirmation_message ) {
$confirmation = substr( $confirmation, 0, strlen( $confirmation ) - 6 );
} //remove the closing div of the message
else {
$confirmation .= "<div id='gforms_confirmation_message' class='gform_confirmation_message_{$form_id}'>";
}
$results = $this->gpoll_get_results( $form['id'], $submitted_fields, $style, $percentages, $counts, $lead );
$confirmation .= $results['summary'] . '</div>';
if ( $has_confirmation_wrapper ) {
$confirmation .= '</div>';
}
} elseif ( ! $display_confirmation && $display_results ) {
//only the results without the confirmation message
$results = $this->gpoll_get_results( $form['id'], $submitted_fields, $style, $percentages, $counts, $lead );
$results_summary = $results['summary'];
$confirmation = sprintf( "<div id='gforms_confirmation_message' class='gform_confirmation_message_{$form_id}'>%s</div>", $results_summary );
} elseif ( ! $display_confirmation && ! $display_results ) {
$confirmation = "<div id='gforms_confirmation_message' class='gform_confirmation_message_{$form_id}'></div>";
}
return $confirmation;
} // end function gpoll_confirmation
/**
* If necessary set a cookie to block repeat submissions.
*
* @param array $entry The current entry object.
* @param array $form The current form object.
*/
public function after_submission( $entry, $form ) {
if ( rgget( 'gf_page' ) == 'preview' ) {
return;
}
$set_cookie = false;
$cookie = '';
$field_values = array();
if ( isset( $_POST['gform_field_values'] ) ) {
$field_values = wp_parse_args( $_POST['gform_field_values'] );
}
$override = false;
if ( rgar( $field_values, 'gpoll_enabled' ) == '1' ) {
$show_results_link = rgar( $field_values, 'gpoll_show_results_link' );
$show_results_link = $show_results_link == '1' ? true : false;
$style = rgar( $field_values, 'gpoll_style' );
$percentages = rgar( $field_values, 'gpoll_percentages' );
$percentages = $percentages == '1' ? true : false;
$counts = rgar( $field_values, 'gpoll_counts' );
$counts = $counts == '1' ? true : false;
$cookie = $field_values['gpoll_cookie'];
$display_results = rgar( $field_values, 'gpoll_display_results' );
$display_results = $display_results == '1' ? true : false;
$display_confirmation = rgar( $field_values, 'gpoll_confirmation' );
$display_confirmation = $display_confirmation == '1' ? true : false;
$checksum = rgar( $field_values, 'gpoll_checksum' );
if ( $checksum == $this->generate_checksum( $display_results, $show_results_link, $cookie, $display_confirmation, $percentages, $counts, $style ) ) {
$set_cookie = true;
$override = true;
}
}
if ( false === $override ) {
if ( $this->get_form_setting( $form, 'blockRepeatVoters' ) ) {
$set_cookie = true;
$cookie = $this->get_form_setting( $form, 'cookie' );
}
}
if ( $set_cookie ) {
$form_id = $form['id'];
$lead_id = $entry['id'];
$server_tz = date_default_timezone_get();
$browser_tz = rgar( $_COOKIE, 'gpoll-timezone' ); // in hours
if ( false === empty( $browser_tz ) ) {
date_default_timezone_set( $browser_tz );
}
$cookie_expiration = strtotime( $cookie );
date_default_timezone_set( $server_tz );
setcookie( 'gpoll_form_' . $form_id, $lead_id, $cookie_expiration, COOKIEPATH, COOKIE_DOMAIN );
}
}
// # ENTRY RELATED --------------------------------------------------------------------------------------------------
/**
* If the field is a Poll type radio, select or checkbox then replace the choice value with the choice text.
*
* @param string $value The field value.
* @param GF_Field|null $field The field object being processed or null.
*
* @return string
*/
public function maybe_format_field_values( $value, $field ) {
if ( is_object( $field ) && $field->type == 'poll' ) {
switch ( $field->inputType ) {
case 'radio' :
case 'select' :
return RGFormsModel::get_choice_text( $field, $value );
case 'checkbox' :
if ( is_array( $value ) ) {
foreach ( $value as &$choice ) {
if ( ! empty( $choice ) ) {
$choice = RGFormsModel::get_choice_text( $field, $choice );
}
}
} else {
foreach ( $field->choices as $choice ) {
$val = rgar( $choice, 'value' );
$text = rgar( $choice, 'text' );
$value = str_replace( $val, $text, $value );
}
}
}
}
return $value;
}
/**
* Format the Poll field values so they use the choice text instead of values before being passed to the third-party.
*
* @param string $value The field value.
* @param array $form The form currently being processed.
* @param array $entry The entry object currently being processed.
* @param string $field_id The ID of the field currently being processed.
*
* @return string
*/
public function addon_field_value( $value, $form, $entry, $field_id, $slug ) {
if ( ! empty( $value ) ) {
$field = RGFormsModel::get_field( $form, $field_id );
return $this->maybe_format_field_values( $value, $field );
}
return $value;
}
/**
* Format the Poll field values so they use the choice text instead of values.
*
* Used for the entry list page, the AWeber, Campaign Monitor, and MailChimp add-ons.
*
* @param string|array $value The field value.
* @param int $form_id The ID of the form currently being processed.
* @param string $field_id The ID of the field currently being processed.
* @param array $entry The entry object currently being processed.
*
* @return string|array
*/
public function display_entries_field_value( $value, $form_id, $field_id, $entry ) {
if ( ! empty( $value ) ) {
global $_form_metas;
if ( ! isset( $_form_metas[ $form_id ] ) ) {
$_form_metas[ $form_id ] = RGFormsModel::get_form_meta( $form_id );
}
$form_meta = $_form_metas[ $form_id ];