Completed
Push — update/editor-blocks-icon-colo... ( 093ab2...3cfb5e )
by
unknown
08:47
created

CrowdsignalShortcode::generate_scripts()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 5
nop 0
dl 0
loc 31
rs 8.8017
c 0
b 0
f 0
1
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2
/**
3
 * Crowdsignal (PollDaddy) shortcode.
4
 *
5
 * Formats:
6
 * [polldaddy type="iframe" survey="EB151947E5950FCF" height="auto" domain="jeherve" id="a-survey-with-branches"]
7
 * [crowdsignal type="iframe" survey="EB151947E5950FCF" height="auto" domain="jeherve" id="a-survey-with-branches"]
8
 * https://polldaddy.com/poll/7910844/
9
 * https://jeherve.survey.fm/a-survey
10
 * https://jeherve.survey.fm/a-survey-with-branches
11
 * [crowdsignal type="iframe" survey="7676FB1FF2B56CE9" height="auto" domain="jeherve" id="a-survey"]
12
 * [crowdsignal survey="7676FB1FF2B56CE9"]
13
 * [polldaddy survey="7676FB1FF2B56CE9"]
14
 * [crowdsignal poll=9541291]
15
 * [crowdsignal poll=9541291 type=slider]
16
 * [crowdsignal rating=8755352]
17
 *
18
 * @package Jetpack
19
 */
20
21
use Automattic\Jetpack\Assets;
22
use Automattic\Jetpack\Constants;
23
24
// Keep compatibility with the PollDaddy plugin.
25
if (
26
	! class_exists( 'CrowdsignalShortcode' )
27
	&& ! class_exists( 'PolldaddyShortcode' )
28
) {
29
	/**
30
	 * Class wrapper for Crowdsignal shortcodes
31
	 */
32
	class CrowdsignalShortcode {
33
34
		/**
35
		 * Should the Crowdsignal JavaScript be added to the page?
36
		 *
37
		 * @var bool
38
		 */
39
		private static $add_script = false;
40
41
		/**
42
		 * Array of Polls / Surveys present on the page, and that need to be added.
43
		 *
44
		 * @var bool|array
45
		 */
46
		private static $scripts = false;
47
48
		/**
49
		 * Add all the actions & register the shortcode.
50
		 */
51
		public function __construct() {
52
			add_action( 'init', array( $this, 'register_scripts' ) );
53
54
			add_shortcode( 'crowdsignal', array( $this, 'crowdsignal_shortcode' ) );
55
			add_shortcode( 'polldaddy', array( $this, 'polldaddy_shortcode' ) );
56
57
			add_filter( 'pre_kses', array( $this, 'crowdsignal_embed_to_shortcode' ) );
58
			add_action( 'wp_enqueue_scripts', array( $this, 'check_infinite' ) );
59
			add_action( 'infinite_scroll_render', array( $this, 'crowdsignal_shortcode_infinite' ), 11 );
60
		}
61
62
		/**
63
		 * Register scripts that may be enqueued later on by the shortcode.
64
		 */
65
		public static function register_scripts() {
66
			wp_register_script(
67
				'crowdsignal-shortcode',
68
				Assets::get_file_url_for_environment( '_inc/build/crowdsignal-shortcode.min.js', '_inc/crowdsignal-shortcode.js' ),
69
				array( 'jquery' ),
70
				JETPACK__VERSION,
71
				true
72
			);
73
			wp_register_script(
74
				'crowdsignal-survey',
75
				Assets::get_file_url_for_environment( '_inc/build/crowdsignal-survey.min.js', '_inc/crowdsignal-survey.js' ),
76
				array(),
77
				JETPACK__VERSION,
78
				true
79
			);
80
			wp_register_script(
81
				'crowdsignal-rating',
82
				'https://polldaddy.com/js/rating/rating.js',
83
				array(),
84
				JETPACK__VERSION,
85
				true
86
			);
87
		}
88
89
		/**
90
		 * JavaScript code for a specific survey / poll.
91
		 *
92
		 * @param array  $settings Array of information about a survey / poll.
93
		 * @param string $survey_link HTML link tag for a specific survey or poll.
94
		 * @param string $survey_url  Link to the survey or poll.
95
		 */
96
		private function get_async_code( array $settings, $survey_link, $survey_url ) {
97
			wp_enqueue_script( 'crowdsignal-survey' );
98
99
			if ( 'button' === $settings['type'] ) {
100
				$placeholder = sprintf(
101
					'<a class="cs-embed pd-embed" href="%1$s" data-settings="%2$s">%3$s</a>',
102
					esc_url( $survey_url ),
103
					esc_attr( wp_json_encode( $settings ) ),
104
					esc_html( $settings['title'] )
105
				);
106
			} else {
107
				$placeholder = sprintf(
108
					'<div class="cs-embed pd-embed" data-settings="%1$s"></div><noscript>%2$s</noscript>',
109
					esc_attr( wp_json_encode( $settings ) ),
110
					$survey_link
111
				);
112
			}
113
114
			return $placeholder;
115
		}
116
117
		/**
118
		 * Crowdsignal Poll Embed script - transforms code that looks like that:
119
		 * <script type="text/javascript" charset="utf-8" async src="http://static.polldaddy.com/p/123456.js"></script>
120
		 * <noscript><a href="http://polldaddy.com/poll/123456/">What is your favourite color?</a></noscript>
121
		 * into the [crowdsignal poll=...] shortcode format
122
		 *
123
		 * @param string $content Post content.
124
		 */
125
		public function crowdsignal_embed_to_shortcode( $content ) {
126
127
			if ( ! is_string( $content ) || false === strpos( $content, 'polldaddy.com/p/' ) ) {
128
				return $content;
129
			}
130
131
			$regexes = array();
132
133
			$regexes[] = '#<script[^>]+?src="https?://(secure|static)\.polldaddy\.com/p/([0-9]+)\.js"[^>]*+>\s*?</script>\r?\n?(<noscript>.*?</noscript>)?#i';
134
135
			$regexes[] = '#&lt;script(?:[^&]|&(?!gt;))+?src="https?://(secure|static)\.polldaddy\.com/p/([0-9]+)\.js"(?:[^&]|&(?!gt;))*+&gt;\s*?&lt;/script&gt;\r?\n?(&lt;noscript&gt;.*?&lt;/noscript&gt;)?#i';
136
137
			foreach ( $regexes as $regex ) {
138
				if ( ! preg_match_all( $regex, $content, $matches, PREG_SET_ORDER ) ) {
139
					continue;
140
				}
141
142
				foreach ( $matches as $match ) {
143
					if ( ! isset( $match[2] ) ) {
144
						continue;
145
					}
146
147
					$id = (int) $match[2];
148
149
					if ( $id > 0 ) {
150
						$content = str_replace( $match[0], " [crowdsignal poll=$id]", $content );
151
						/** This action is documented in modules/shortcodes/youtube.php */
152
						do_action( 'jetpack_embed_to_shortcode', 'crowdsignal', $id );
153
					}
154
				}
155
			}
156
157
			return $content;
158
		}
159
160
		/**
161
		 * Support for legacy Polldaddy shortcode.
162
		 *
163
		 * @param array $atts Shortcode attributes.
164
		 */
165
		public function polldaddy_shortcode( $atts ) {
166
			if ( ! is_array( $atts ) ) {
167
				return '<!-- Polldaddy shortcode passed invalid attributes -->';
168
			}
169
170
			$atts['site'] = 'polldaddy.com';
171
			return $this->crowdsignal_shortcode( $atts );
172
		}
173
174
		/**
175
		 * Shortcode for Crowdsignal
176
		 * [crowdsignal poll|survey|rating="123456"]
177
		 *
178
		 * @param array $atts Shortcode attributes.
179
		 */
180
		public function crowdsignal_shortcode( $atts ) {
181
			global $post;
182
			global $content_width;
183
184
			if ( ! is_array( $atts ) ) {
185
				return '<!-- Crowdsignal shortcode passed invalid attributes -->';
186
			}
187
188
			$attributes = shortcode_atts(
189
				array(
190
					'survey'     => null,
191
					'link_text'  => esc_html__( 'Take Our Survey', 'jetpack' ),
192
					'poll'       => 'empty',
193
					'rating'     => 'empty',
194
					'unique_id'  => null,
195
					'item_id'    => null,
196
					'title'      => null,
197
					'permalink'  => null,
198
					'cb'         => 0, // cache buster. Helps with testing.
199
					'type'       => 'button',
200
					'body'       => '',
201
					'button'     => '',
202
					'text_color' => '000000',
203
					'back_color' => 'FFFFFF',
204
					'align'      => '',
205
					'style'      => '',
206
					'width'      => $content_width,
207
					'height'     => floor( $content_width * 3 / 4 ),
208
					'delay'      => 100,
209
					'visit'      => 'single',
210
					'domain'     => '',
211
					'id'         => '',
212
					'site'       => 'crowdsignal.com',
213
				),
214
				$atts,
215
				'crowdsignal'
216
			);
217
218
			$inline = ! in_the_loop()
219
				&& ! Constants::is_defined( 'TESTING_IN_JETPACK' );
220
221
			$no_script       = false;
222
			$infinite_scroll = false;
223
224
			if ( is_home() && current_theme_supports( 'infinite-scroll' ) ) {
225
				$infinite_scroll = true;
226
			}
227
228
			if ( function_exists( 'get_option' ) && get_option( 'polldaddy_load_poll_inline' ) ) {
229
				$inline = true;
230
			}
231
232
			if ( is_feed() || ( defined( 'DOING_AJAX' ) && ! $infinite_scroll ) ) {
233
				$no_script = false;
234
			}
235
236
			self::$add_script = $infinite_scroll;
237
238
			/*
239
			 * Rating embed.
240
			 */
241
			if ( intval( $attributes['rating'] ) > 0 && ! $no_script ) {
242
243
				if ( empty( $attributes['unique_id'] ) ) {
244
					$attributes['unique_id'] = is_page() ? 'wp-page-' . $post->ID : 'wp-post-' . $post->ID;
245
				}
246
247
				if ( empty( $attributes['item_id'] ) ) {
248
					$attributes['item_id'] = is_page() ? '_page_' . $post->ID : '_post_' . $post->ID;
249
				}
250
251
				if ( empty( $attributes['title'] ) ) {
252
					/** This filter is documented in core/src/wp-includes/general-template.php */
253
					$attributes['title'] = apply_filters( 'wp_title', $post->post_title, '', '' );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with ''.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
254
				}
255
256
				if ( empty( $attributes['permalink'] ) ) {
257
					$attributes['permalink'] = get_permalink( $post->ID );
258
				}
259
260
				$rating    = intval( $attributes['rating'] );
261
				$unique_id = preg_replace( '/[^\-_a-z0-9]/i', '', wp_strip_all_tags( $attributes['unique_id'] ) );
262
				$item_id   = wp_strip_all_tags( $attributes['item_id'] );
263
				$item_id   = preg_replace( '/[^_a-z0-9]/i', '', $item_id );
264
265
				$settings = wp_json_encode(
266
					array(
267
						'id'        => $rating,
268
						'unique_id' => $unique_id,
269
						'title'     => rawurlencode( trim( $attributes['title'] ) ),
270
						'permalink' => esc_url( $attributes['permalink'] ),
271
						'item_id'   => $item_id,
272
					)
273
				);
274
275
				$item_id = esc_js( $item_id );
276
277
				if (
278
					class_exists( 'Jetpack_AMP_Support' )
279
					&& Jetpack_AMP_Support::is_amp_request()
280
				) {
281
					return sprintf(
282
						'<a href="%s" target="_blank">%s</a>',
283
						esc_url( $attributes['permalink'] ),
284
						esc_html( trim( $attributes['title'] ) )
285
					);
286
				} elseif ( $inline ) {
287
					$rating_js  = "<!--//--><![CDATA[//><!--\n";
288
					$rating_js .= "PDRTJS_settings_{$rating}{$item_id}={$settings};";
289
					$rating_js .= "\n//--><!]]>";
290
291
					wp_enqueue_script( 'crowdsignal-rating' );
292
					wp_add_inline_script(
293
						'crowdsignal-rating',
294
						$rating_js,
295
						'before'
296
					);
297
298
					return sprintf(
299
						'<div class="cs-rating pd-rating" id="pd_rating_holder_%1$d%2$s"></div>',
300
						absint( $rating ),
301
						esc_attr( $item_id )
302
					);
303
				} else {
304
					if ( false === self::$scripts ) {
305
						self::$scripts = array();
306
					}
307
308
					$data = array(
309
						'id'       => $rating,
310
						'item_id'  => $item_id,
311
						'settings' => $settings,
312
					);
313
314
					self::$scripts['rating'][] = $data;
315
316
					add_action( 'wp_footer', array( $this, 'generate_scripts' ) );
317
318
					if ( $infinite_scroll ) {
319
						return sprintf(
320
							'<div class="cs-rating pd-rating" id="pd_rating_holder_%1$d%2$s" data-settings="%3$s"></div>',
321
							absint( $rating ),
322
							esc_attr( $item_id ),
323
							esc_attr( wp_json_encode( $data ) )
324
						);
325
					} else {
326
						return sprintf(
327
							'<div class="cs-rating pd-rating" id="pd_rating_holder_%1$d%2$s"></div>',
328
							absint( $rating ),
329
							esc_attr( $item_id )
330
						);
331
					}
332
				}
333
			} elseif ( intval( $attributes['poll'] ) > 0 ) {
334
				/*
335
				 * Poll embed.
336
				 */
337
338
				if ( empty( $attributes['title'] ) ) {
339
					$attributes['title'] = esc_html__( 'Take Our Poll', 'jetpack' );
340
				}
341
342
				$poll = intval( $attributes['poll'] );
343
344
				if ( 'crowdsignal.com' === $attributes['site'] ) {
345
					$poll_url = sprintf( 'https://poll.fm/%d', $poll );
346
				} else {
347
					$poll_url = sprintf( 'https://polldaddy.com/p/%d', $poll );
348
				}
349
350
				$poll_js   = sprintf( 'https://secure.polldaddy.com/p/%d.js', $poll );
351
				$poll_link = sprintf(
352
					'<a href="%s" target="_blank">%s</a>',
353
					esc_url( $poll_url ),
354
					esc_html( $attributes['title'] )
355
				);
356
357
				if (
358
					$no_script
359
					|| ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() )
360
				) {
361
					return $poll_link;
362
				} else {
363
					/*
364
					 * Slider poll.
365
					 */
366
					if (
367
						'slider' === $attributes['type']
368
						&& ! $inline
369
					) {
370
371
						if ( ! in_array(
372
							$attributes['visit'],
373
							array( 'single', 'multiple' ),
374
							true
375
						) ) {
376
							$attributes['visit'] = 'single';
377
						}
378
379
						$settings = array(
380
							'type'  => 'slider',
381
							'embed' => 'poll',
382
							'delay' => intval( $attributes['delay'] ),
383
							'visit' => $attributes['visit'],
384
							'id'    => intval( $poll ),
385
							'site'  => $attributes['site'],
386
						);
387
388
						return $this->get_async_code( $settings, $poll_link, $poll_url );
389
					} else {
390
						if ( 1 === $attributes['cb'] ) {
391
							$attributes['cb'] = '?cb=' . mktime();
392
						} else {
393
							$attributes['cb'] = false;
394
						}
395
						$margins = '';
396
						$float   = '';
397
398
						if ( in_array(
399
							$attributes['align'],
400
							array( 'right', 'left' ),
401
							true
402
						) ) {
403
							$float = sprintf( 'float: %s;', $attributes['align'] );
404
405
							if ( 'left' === $attributes['align'] ) {
406
								$margins = 'margin: 0px 10px 0px 0px;';
407
							} elseif ( 'right' === $attributes['align'] ) {
408
								$margins = 'margin: 0px 0px 0px 10px';
409
							}
410
						}
411
412
						/*
413
						 * Force the normal style embed on single posts/pages
414
						 * otherwise it's not rendered on infinite scroll themed blogs
415
						 * ('infinite_scroll_render' isn't fired)
416
						 */
417
						if ( is_singular() ) {
418
							$inline = true;
419
						}
420
421
						if ( false === $attributes['cb'] && ! $inline ) {
422
							if ( false === self::$scripts ) {
423
								self::$scripts = array();
424
							}
425
426
							$data = array( 'url' => $poll_js );
427
428
							self::$scripts['poll'][ intval( $poll ) ] = $data;
429
430
							add_action( 'wp_footer', array( $this, 'generate_scripts' ) );
431
432
							wp_enqueue_script( 'crowdsignal-shortcode' );
433
							wp_localize_script(
434
								'crowdsignal-shortcode',
435
								'crowdsignal_shortcode_options',
436
								array(
437
									'script_url' => esc_url_raw(
438
										Assets::get_file_url_for_environment(
439
											'_inc/build/polldaddy-shortcode.min.js',
440
											'_inc/polldaddy-shortcode.js'
441
										)
442
									),
443
								)
444
							);
445
446
							/**
447
							 * Hook into the Crowdsignal shortcode before rendering.
448
							 *
449
							 * @since 8.4.0
450
							 *
451
							 * @param int $poll Poll ID.
452
							 */
453
							do_action( 'crowdsignal_shortcode_before', intval( $poll ) );
454
455
							return sprintf(
456
								'<a name="pd_a_%1$d"></a><div class="CSS_Poll PDS_Poll" id="PDI_container%1$d" data-settings="%2$s" style="%3$s%4$s"></div><div id="PD_superContainer"></div><noscript>%5$s</noscript>',
457
								absint( $poll ),
458
								esc_attr( wp_json_encode( $data ) ),
459
								$float,
460
								$margins,
461
								$poll_link
462
							);
463
						} else {
464
							if ( $inline ) {
465
								$attributes['cb'] = '';
466
							}
467
468
							wp_enqueue_script(
469
								'crowdsignal-' . absint( $poll ),
470
								esc_url( $poll_js . $attributes['cb'] ),
471
								array(),
472
								JETPACK__VERSION,
473
								true
474
							);
475
476
							/** This action is already documented in modules/shortcodes/crowdsignal.php */
477
							do_action( 'crowdsignal_shortcode_before', intval( $poll ) );
478
479
							return sprintf(
480
								'<a id="pd_a_%1$s"></a><div class="CSS_Poll PDS_Poll" id="PDI_container%1$s" style="%2$s%3$s"></div><div id="PD_superContainer"></div><noscript>%4$s</noscript>',
481
								absint( $poll ),
482
								$float,
483
								$margins,
484
								$poll_link
485
							);
486
						}
487
					}
488
				}
489
			} elseif ( ! empty( $attributes['survey'] ) ) {
490
				/*
491
				 * Survey embed.
492
				 */
493
494
				if ( in_array(
495
					$attributes['type'],
496
					array( 'iframe', 'button', 'banner', 'slider' ),
497
					true
498
				) ) {
499
500
					if ( empty( $attributes['title'] ) ) {
501
						$attributes['title'] = esc_html__( 'Take Our Survey', 'jetpack' );
502
						if ( ! empty( $attributes['link_text'] ) ) {
503
							$attributes['title'] = $attributes['link_text'];
504
						}
505
					}
506
507
					if (
508
						'banner' === $attributes['type']
509
						|| 'slider' === $attributes['type']
510
					) {
511
						$inline = false;
0 ignored issues
show
Unused Code introduced by
$inline is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
512
					}
513
514
					$survey = preg_replace( '/[^a-f0-9]/i', '', $attributes['survey'] );
515
516
					if ( 'crowdsignal.com' === $attributes['site'] ) {
517
						$survey_url = 'https://survey.fm/' . $survey;
518
					} else {
519
						$survey_url = 'https://polldaddy.com/s/' . $survey;
520
					}
521
522
					$survey_link = sprintf(
523
						'<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
524
						esc_url( $survey_url ),
525
						esc_html( $attributes['title'] )
526
					);
527
528
					$settings = array();
529
530
					if ( 'iframe' === $attributes['type'] ) {
531
						if ( 'auto' !== $attributes['height'] ) {
532 View Code Duplication
							if (
533
								isset( $content_width )
534
								&& is_numeric( $attributes['width'] )
535
								&& $attributes['width'] > $content_width
536
							) {
537
								$attributes['width'] = $content_width;
538
							}
539
540
							if ( ! $attributes['width'] ) {
541
								$attributes['width'] = '100%';
542
							} else {
543
								$attributes['width'] = (int) $attributes['width'];
544
							}
545
546
							if ( ! $attributes['height'] ) {
547
								$attributes['height'] = '600';
548
							} else {
549
								$attributes['height'] = (int) $attributes['height'];
550
							}
551
552
							return sprintf(
553
								'<iframe src="%1$s?iframe=1" frameborder="0" width="%2$d" height="%3$d" scrolling="auto" allowtransparency="true" marginheight="0" marginwidth="0">%4$s</iframe>',
554
								esc_url( $survey_url ),
555
								absint( $attributes['width'] ),
556
								absint( $attributes['height'] ),
557
								$survey_link
558
							);
559
						} elseif (
560
							! empty( $attributes['domain'] )
561
							&& ! empty( $attributes['id'] )
562
						) {
563
							$domain = preg_replace( '/[^a-z0-9\-]/i', '', $attributes['domain'] );
564
							$id     = preg_replace( '/[\/\?&\{\}]/', '', $attributes['id'] );
565
566
							$auto_src = esc_url( "https://{$domain}.survey.fm/{$id}" );
567
							$auto_src = wp_parse_url( $auto_src );
568
569
							if ( ! is_array( $auto_src ) || 0 === count( $auto_src ) ) {
570
								return '<!-- no crowdsignal output -->';
571
							}
572
573
							if ( ! isset( $auto_src['host'] ) || ! isset( $auto_src['path'] ) ) {
574
								return '<!-- no crowdsignal output -->';
575
							}
576
577
							$domain = $auto_src['host'] . '/';
578
							$id     = ltrim( $auto_src['path'], '/' );
579
580
							$settings = array(
581
								'type'   => $attributes['type'],
582
								'auto'   => true,
583
								'domain' => $domain,
584
								'id'     => $id,
585
								'site'   => $attributes['site'],
586
							);
587
						}
588
					} else {
589
						$text_color = preg_replace( '/[^a-f0-9]/i', '', $attributes['text_color'] );
590
						$back_color = preg_replace( '/[^a-f0-9]/i', '', $attributes['back_color'] );
591
592
						if (
593
							! in_array(
594
								$attributes['align'],
595
								array(
596
									'right',
597
									'left',
598
									'top-left',
599
									'top-right',
600
									'middle-left',
601
									'middle-right',
602
									'bottom-left',
603
									'bottom-right',
604
								),
605
								true
606
							)
607
						) {
608
							$attributes['align'] = '';
609
						}
610
611
						if (
612
							! in_array(
613
								$attributes['style'],
614
								array(
615
									'inline',
616
									'side',
617
									'corner',
618
									'rounded',
619
									'square',
620
								),
621
								true
622
							)
623
						) {
624
							$attributes['style'] = '';
625
						}
626
627
						$settings = array_filter(
628
							array(
629
								'title'      => wp_strip_all_tags( $attributes['title'] ),
630
								'type'       => $attributes['type'],
631
								'body'       => wp_strip_all_tags( $attributes['body'] ),
632
								'button'     => wp_strip_all_tags( $attributes['button'] ),
633
								'text_color' => $text_color,
634
								'back_color' => $back_color,
635
								'align'      => $attributes['align'],
636
								'style'      => $attributes['style'],
637
								'id'         => $survey,
638
								'site'       => $attributes['site'],
639
							)
640
						);
641
					}
642
643
					if ( empty( $settings ) ) {
644
						return '<!-- no crowdsignal output -->';
645
					}
646
647
					return $this->get_async_code( $settings, $survey_link, $survey_url );
648
				}
649
			} else {
650
				return '<!-- no crowdsignal output -->';
651
			}
652
		}
653
654
		/**
655
		 * Enqueue JavaScript containing all ratings / polls on the page.
656
		 * Hooked into wp_footer
657
		 */
658
		public function generate_scripts() {
659
			if ( is_array( self::$scripts ) ) {
660
				if ( isset( self::$scripts['rating'] ) ) {
661
					$script = "<!--//--><![CDATA[//><!--\n";
662
					foreach ( self::$scripts['rating'] as $rating ) {
663
						$script .= "PDRTJS_settings_{$rating['id']}{$rating['item_id']}={$rating['settings']}; if ( typeof PDRTJS_RATING !== 'undefined' ){if ( typeof PDRTJS_{$rating['id']}{$rating['item_id']} == 'undefined' ){PDRTJS_{$rating['id']}{$rating['item_id']} = new PDRTJS_RATING( PDRTJS_settings_{$rating['id']}{$rating['item_id']} );}}";
664
					}
665
					$script .= "\n//--><!]]>";
666
667
					wp_enqueue_script( 'crowdsignal-rating' );
668
					wp_add_inline_script(
669
						'crowdsignal-rating',
670
						$script,
671
						'before'
672
					);
673
				}
674
675
				if ( isset( self::$scripts['poll'] ) ) {
676
					foreach ( self::$scripts['poll'] as $poll_id => $poll ) {
677
						wp_enqueue_script(
678
							'crowdsignal-' . absint( $poll_id ),
679
							esc_url( $poll['url'] ),
680
							array(),
681
							JETPACK__VERSION,
682
							true
683
						);
684
					}
685
				}
686
			}
687
			self::$scripts = false;
688
		}
689
690
		/**
691
		 * If the theme uses infinite scroll, include jquery at the start
692
		 */
693
		public function check_infinite() {
694
			if (
695
				current_theme_supports( 'infinite-scroll' )
696
				&& class_exists( 'The_Neverending_Home_Page' )
697
				&& The_Neverending_Home_Page::archive_supports_infinity()
698
			) {
699
				wp_enqueue_script( 'jquery' );
700
			}
701
		}
702
703
		/**
704
		 * Dynamically load the .js, if needed
705
		 *
706
		 * This hooks in late (priority 11) to infinite_scroll_render to determine
707
		 * a posteriori if a shortcode has been called.
708
		 */
709
		public function crowdsignal_shortcode_infinite() {
710
			// only try to load if a shortcode has been called and theme supports infinite scroll.
711
			if ( self::$add_script ) {
712
				wp_enqueue_script( 'crowdsignal-shortcode' );
713
				wp_localize_script(
714
					'crowdsignal-shortcode',
715
					'crowdsignal_shortcode_options',
716
					array(
717
						'script_url' => esc_url_raw(
718
							Assets::get_file_url_for_environment(
719
								'_inc/build/polldaddy-shortcode.min.js',
720
								'_inc/polldaddy-shortcode.js'
721
							)
722
						),
723
					)
724
				);
725
			}
726
		}
727
	}
728
729
	// Kick it all off.
730
	new CrowdsignalShortcode();
731
732
	if ( ! function_exists( 'crowdsignal_link' ) ) {
733
		/**
734
		 * Replace link with shortcode.
735
		 * Examples: https://poll.fm/10499328 | https://7iger.survey.fm/test-embed
736
		 *
737
		 * @param string $content Post content.
738
		 */
739
		function crowdsignal_link( $content ) {
740
			if (
741
				class_exists( 'Jetpack_AMP_Support' )
742
				&& Jetpack_AMP_Support::is_amp_request()
743
			) {
744
				return $content;
745
			}
746
747
			// Replace poll links.
748
			$content = jetpack_preg_replace_outside_tags(
749
				'!(?:\n|\A)https?://(polldaddy\.com/poll|poll\.fm)/([0-9]+?)(/.*)?(?:\n|\Z)!i',
750
				'[crowdsignal poll=$2]',
751
				$content
752
			);
753
754
			// Replace survey.fm links.
755
			$content = preg_replace(
756
				'!(?:\n|\A)https?://(.*).survey.fm/(.*)(/.*)?(?:\n|\Z)!i',
757
				'[crowdsignal type="iframe" survey="true" height="auto" domain="$1" id="$2"]',
758
				$content
759
			);
760
761
			return $content;
762
		}
763
764
		// higher priority because we need it before auto-link and autop get to it.
765
		add_filter( 'the_content', 'crowdsignal_link', 1 );
766
		add_filter( 'the_content_rss', 'crowdsignal_link', 1 );
767
	}
768
}
769