CrowdsignalShortcode::polldaddy_shortcode()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 8
rs 10
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 automattic/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 ( (int) $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    = (int) $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 ( (int) $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 = (int) $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' => (int) $attributes['delay'],
383
							'visit' => $attributes['visit'],
384
							'id'    => (int) $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=' . time();
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'][ (int) $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', (int) $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', (int) $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_url = '';
515
516
					if ( 'true' !== $attributes['survey'] ) {
517
						$survey = preg_replace( '/[^a-f0-9]/i', '', $attributes['survey'] );
518
519
						if ( 'crowdsignal.com' === $attributes['site'] ) {
520
							$survey_url = 'https://survey.fm/' . $survey;
521
						} else {
522
							$survey_url = 'https://polldaddy.com/s/' . $survey;
523
						}
524
					} else {
525
						if ( isset( $attributes['domain'] ) && isset( $attributes['id'] ) ) {
526
							$survey_url = 'https://' . $attributes['domain'] . '.survey.fm/' . $attributes['id'];
527
						}
528
					}
529
530
					$survey_link = sprintf(
531
						'<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
532
						esc_url( $survey_url ),
533
						esc_html( $attributes['title'] )
534
					);
535
536
					$settings = array();
537
538
					if ( 'iframe' === $attributes['type'] ) {
539
						if ( 'auto' !== $attributes['height'] ) {
540 View Code Duplication
							if (
541
								isset( $content_width )
542
								&& is_numeric( $attributes['width'] )
543
								&& $attributes['width'] > $content_width
544
							) {
545
								$attributes['width'] = $content_width;
546
							}
547
548
							if ( ! $attributes['width'] ) {
549
								$attributes['width'] = '100%';
550
							} else {
551
								$attributes['width'] = (int) $attributes['width'];
552
							}
553
554
							if ( ! $attributes['height'] ) {
555
								$attributes['height'] = '600';
556
							} else {
557
								$attributes['height'] = (int) $attributes['height'];
558
							}
559
560
							return sprintf(
561
								'<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>',
562
								esc_url( $survey_url ),
563
								absint( $attributes['width'] ),
564
								absint( $attributes['height'] ),
565
								$survey_link
566
							);
567
						} elseif (
568
							! empty( $attributes['domain'] )
569
							&& ! empty( $attributes['id'] )
570
						) {
571
							$domain = preg_replace( '/[^a-z0-9\-]/i', '', $attributes['domain'] );
572
							$id     = preg_replace( '/[\/\?&\{\}]/', '', $attributes['id'] );
573
574
							$auto_src = esc_url( "https://{$domain}.survey.fm/{$id}" );
575
							$auto_src = wp_parse_url( $auto_src );
576
577
							if ( ! is_array( $auto_src ) || 0 === count( $auto_src ) ) {
578
								return '<!-- no crowdsignal output -->';
579
							}
580
581
							if ( ! isset( $auto_src['host'] ) || ! isset( $auto_src['path'] ) ) {
582
								return '<!-- no crowdsignal output -->';
583
							}
584
585
							$domain = $auto_src['host'] . '/';
586
							$id     = ltrim( $auto_src['path'], '/' );
587
588
							$settings = array(
589
								'type'   => $attributes['type'],
590
								'auto'   => true,
591
								'domain' => $domain,
592
								'id'     => $id,
593
								'site'   => $attributes['site'],
594
							);
595
						}
596
					} else {
597
						$text_color = preg_replace( '/[^a-f0-9]/i', '', $attributes['text_color'] );
598
						$back_color = preg_replace( '/[^a-f0-9]/i', '', $attributes['back_color'] );
599
600
						if (
601
							! in_array(
602
								$attributes['align'],
603
								array(
604
									'right',
605
									'left',
606
									'top-left',
607
									'top-right',
608
									'middle-left',
609
									'middle-right',
610
									'bottom-left',
611
									'bottom-right',
612
								),
613
								true
614
							)
615
						) {
616
							$attributes['align'] = '';
617
						}
618
619
						if (
620
							! in_array(
621
								$attributes['style'],
622
								array(
623
									'inline',
624
									'side',
625
									'corner',
626
									'rounded',
627
									'square',
628
								),
629
								true
630
							)
631
						) {
632
							$attributes['style'] = '';
633
						}
634
635
						$settings = array_filter(
636
							array(
637
								'title'      => wp_strip_all_tags( $attributes['title'] ),
638
								'type'       => $attributes['type'],
639
								'body'       => wp_strip_all_tags( $attributes['body'] ),
640
								'button'     => wp_strip_all_tags( $attributes['button'] ),
641
								'text_color' => $text_color,
642
								'back_color' => $back_color,
643
								'align'      => $attributes['align'],
644
								'style'      => $attributes['style'],
645
								'id'         => $survey,
0 ignored issues
show
Bug introduced by
The variable $survey does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
646
								'site'       => $attributes['site'],
647
							)
648
						);
649
					}
650
651
					if ( empty( $settings ) ) {
652
						return '<!-- no crowdsignal output -->';
653
					}
654
655
					return $this->get_async_code( $settings, $survey_link, $survey_url );
656
				}
657
			} else {
658
				return '<!-- no crowdsignal output -->';
659
			}
660
		}
661
662
		/**
663
		 * Enqueue JavaScript containing all ratings / polls on the page.
664
		 * Hooked into wp_footer
665
		 */
666
		public function generate_scripts() {
667
			if ( is_array( self::$scripts ) ) {
668
				if ( isset( self::$scripts['rating'] ) ) {
669
					$script = "<!--//--><![CDATA[//><!--\n";
670
					foreach ( self::$scripts['rating'] as $rating ) {
671
						$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']} );}}";
672
					}
673
					$script .= "\n//--><!]]>";
674
675
					wp_enqueue_script( 'crowdsignal-rating' );
676
					wp_add_inline_script(
677
						'crowdsignal-rating',
678
						$script,
679
						'before'
680
					);
681
				}
682
683
				if ( isset( self::$scripts['poll'] ) ) {
684
					foreach ( self::$scripts['poll'] as $poll_id => $poll ) {
685
						wp_enqueue_script(
686
							'crowdsignal-' . absint( $poll_id ),
687
							esc_url( $poll['url'] ),
688
							array(),
689
							JETPACK__VERSION,
690
							true
691
						);
692
					}
693
				}
694
			}
695
			self::$scripts = false;
696
		}
697
698
		/**
699
		 * If the theme uses infinite scroll, include jquery at the start
700
		 */
701
		public function check_infinite() {
702
			if (
703
				current_theme_supports( 'infinite-scroll' )
704
				&& class_exists( 'The_Neverending_Home_Page' )
705
				&& The_Neverending_Home_Page::archive_supports_infinity()
706
			) {
707
				wp_enqueue_script( 'jquery' );
708
			}
709
		}
710
711
		/**
712
		 * Dynamically load the .js, if needed
713
		 *
714
		 * This hooks in late (priority 11) to infinite_scroll_render to determine
715
		 * a posteriori if a shortcode has been called.
716
		 */
717
		public function crowdsignal_shortcode_infinite() {
718
			// only try to load if a shortcode has been called and theme supports infinite scroll.
719
			if ( self::$add_script ) {
720
				wp_enqueue_script( 'crowdsignal-shortcode' );
721
				wp_localize_script(
722
					'crowdsignal-shortcode',
723
					'crowdsignal_shortcode_options',
724
					array(
725
						'script_url' => esc_url_raw(
726
							Assets::get_file_url_for_environment(
727
								'_inc/build/polldaddy-shortcode.min.js',
728
								'_inc/polldaddy-shortcode.js'
729
							)
730
						),
731
					)
732
				);
733
			}
734
		}
735
	}
736
737
	// Kick it all off.
738
	new CrowdsignalShortcode();
739
740
	if ( ! function_exists( 'crowdsignal_link' ) ) {
741
		/**
742
		 * Replace link with shortcode.
743
		 * Examples: https://poll.fm/10499328 | https://7iger.survey.fm/test-embed
744
		 *
745
		 * @param string $content Post content.
746
		 */
747
		function crowdsignal_link( $content ) {
748
			if (
749
				class_exists( 'Jetpack_AMP_Support' )
750
				&& Jetpack_AMP_Support::is_amp_request()
751
			) {
752
				return $content;
753
			}
754
755
			// Replace poll links.
756
			$content = jetpack_preg_replace_outside_tags(
757
				'!(?:\n|\A)https?://(polldaddy\.com/poll|poll\.fm)/([0-9]+?)(/.*)?(?:\n|\Z)!i',
758
				'[crowdsignal poll=$2]',
759
				$content
760
			);
761
762
			// Replace survey.fm links.
763
			$content = preg_replace(
764
				'!(?:\n|\A)https?://(.*).survey.fm/(.*)(/.*)?(?:\n|\Z)!i',
765
				'[crowdsignal type="iframe" survey="true" height="auto" domain="$1" id="$2"]',
766
				$content
767
			);
768
769
			return $content;
770
		}
771
772
		// higher priority because we need it before auto-link and autop get to it.
773
		add_filter( 'the_content', 'crowdsignal_link', 1 );
774
		add_filter( 'the_content_rss', 'crowdsignal_link', 1 );
775
	}
776
}
777