Completed
Push — add/gdpr-ads-compliance ( 65c5dd...c52a1e )
by
unknown
17:44 queued 08:35
created

WordAds::get_ad()   C

Complexity

Conditions 17
Paths 40

Size

Total Lines 54
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 17
eloc 37
nc 40
nop 2
dl 0
loc 54
rs 6.6619
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
define( 'WORDADS_ROOT', dirname( __FILE__ ) );
4
define( 'WORDADS_BASENAME', plugin_basename( __FILE__ ) );
5
define( 'WORDADS_FILE_PATH', WORDADS_ROOT . '/' . basename( __FILE__ ) );
6
define( 'WORDADS_URL', plugins_url( '/', __FILE__ ) );
7
define( 'WORDADS_API_TEST_ID', '26942' );
8
define( 'WORDADS_API_TEST_ID2', '114160' );
9
10
require_once( WORDADS_ROOT . '/php/widgets.php' );
11
require_once( WORDADS_ROOT . '/php/api.php' );
12
require_once( WORDADS_ROOT . '/php/cron.php' );
13
14
class WordAds {
15
16
	public $params = null;
17
18
	/**
19
	 * Array of supported ad types.
20
	 *
21
	 * @var array
22
	 */
23
	public static $ad_tag_ids = array(
24
		'mrec' => array(
25
			'tag'       => '300x250_mediumrectangle',
26
			'height'    => '250',
27
			'width'     => '300',
28
		),
29
		'lrec' => array(
30
			'tag'       => '336x280_largerectangle',
31
			'height'    => '280',
32
			'width'     => '336',
33
		),
34
		'leaderboard' => array(
35
			'tag'       => '728x90_leaderboard',
36
			'height'    => '90',
37
			'width'     => '728',
38
		),
39
		'wideskyscraper' => array(
40
			'tag'       => '160x600_wideskyscraper',
41
			'height'    => '600',
42
			'width'     => '160',
43
		),
44
	);
45
46
	/**
47
	 * Convenience function for grabbing options from params->options
48
	 *
49
	 * @param  string $option the option to grab
50
	 * @param  mixed  $default (optional)
51
	 * @return option or $default if not set
52
	 *
53
	 * @since 4.5.0
54
	 */
55
	function option( $option, $default = false ) {
56
		if ( ! isset( $this->params->options[ $option ] ) ) {
57
			return $default;
58
		}
59
60
		return $this->params->options[ $option ];
61
	}
62
63
	/**
64
	 * Instantiate the plugin
65
	 *
66
	 * @since 4.5.0
67
	 */
68
	function __construct() {
69
		add_action( 'init', array( $this, 'init' ) );
70
	}
71
72
	/**
73
	 * Code to run on WordPress 'init' hook
74
	 *
75
	 * @since 4.5.0
76
	 */
77
	function init() {
78
		// bail on infinite scroll
79
		if ( self::is_infinite_scroll() ) {
80
			return;
81
		}
82
83
		require_once( WORDADS_ROOT . '/php/params.php' );
84
		$this->params = new WordAds_Params();
85
86
		if ( is_admin() ) {
87
			require_once( WORDADS_ROOT . '/php/admin.php' );
88
			return;
89
		}
90
91
		if ( $this->should_bail() ) {
92
			return;
93
		}
94
95
		$this->insert_adcode();
96
	}
97
98
	/**
99
	 * Check for Jetpack's The_Neverending_Home_Page and use got_infinity
100
	 *
101
	 * @return boolean true if load came from infinite scroll
102
	 *
103
	 * @since 4.5.0
104
	 */
105
	public static function is_infinite_scroll() {
106
		return class_exists( 'The_Neverending_Home_Page' ) && The_Neverending_Home_Page::got_infinity();
107
	}
108
109
	/**
110
	 * Add the actions/filters to insert the ads. Checks for mobile or desktop.
111
	 *
112
	 * @since 4.5.0
113
	 */
114
	private function insert_adcode() {
115
		add_action( 'wp_head',              array( $this, 'insert_head_meta' ), 20 );
116
		add_action( 'wp_head',              array( $this, 'insert_head_iponweb' ), 30 );
117
		add_action( 'wp_enqueue_scripts',   array( $this, 'enqueue_scripts' ) );
118
119
		/**
120
		 * Filters enabling ads in `the_content` filter
121
		 *
122
		 * @see https://jetpack.com/support/ads/
123
		 *
124
		 * @module wordads
125
		 *
126
		 * @since 5.8.0
127
		 *
128
		 * @param bool True to disable ads in `the_content`
129
		 */
130
		if ( ! apply_filters( 'wordads_content_disable', false ) ) {
131
			add_filter( 'the_content', array( $this, 'insert_ad' ) );
132
		}
133
134
		/**
135
		 * Filters enabling ads in `the_excerpt` filter
136
		 *
137
		 * @see https://jetpack.com/support/ads/
138
		 *
139
		 * @module wordads
140
		 *
141
		 * @since 5.8.0
142
		 *
143
		 * @param bool True to disable ads in `the_excerpt`
144
		 */
145
		if ( ! apply_filters( 'wordads_excerpt_disable', false ) ) {
146
			add_filter( 'the_excerpt', array( $this, 'insert_ad' ) );
147
		}
148
149
		if ( $this->option( 'enable_header_ad', true ) ) {
150
			switch ( get_stylesheet() ) {
151
				case 'twentyseventeen':
152
				case 'twentyfifteen':
153
				case 'twentyfourteen':
154
					add_action( 'wp_footer', array( $this, 'insert_header_ad_special' ) );
155
					break;
156
				default:
157
					add_action( 'wp_head', array( $this, 'insert_header_ad' ), 100 );
158
					break;
159
			}
160
		}
161
	}
162
163
	/**
164
	 * Register desktop scripts and styles
165
	 *
166
	 * @since 4.5.0
167
	 */
168
	function enqueue_scripts() {
169
		wp_enqueue_style(
170
			'wordads',
171
			WORDADS_URL . 'css/style.css',
172
			array(),
173
			'2015-12-18'
174
		);
175
	}
176
177
	/**
178
	 * IPONWEB metadata used by the various scripts
179
	 * @return [type] [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
180
	 */
181
	function insert_head_meta() {
182
		$themename = esc_js( get_stylesheet() );
183
		$pagetype = intval( $this->params->get_page_type_ipw() );
184
		$data_tags = ( $this->params->cloudflare ) ? ' data-cfasync="false"' : '';
185
		$site_id = $this->params->blog_id;
186
		$consent = isset( $_COOKIE['personalized-ads-consent'] );
187
		echo <<<HTML
188
		<script$data_tags type="text/javascript">
189
			var __ATA_PP = { pt: $pagetype, ht: 2, tn: '$themename', amp: false, siteid: $site_id, consent: $consent };
190
			var __ATA = __ATA || {};
191
			__ATA.cmd = __ATA.cmd || [];
192
			__ATA.criteo = __ATA.criteo || {};
193
			__ATA.criteo.cmd = __ATA.criteo.cmd || [];
194
		</script>
195
HTML;
196
	}
197
198
	/**
199
	 * IPONWEB scripts in <head>
200
	 *
201
	 * @since 4.5.0
202
	 */
203
	function insert_head_iponweb() {
204
		$data_tags = ( $this->params->cloudflare ) ? ' data-cfasync="false"' : '';
205
		echo <<<HTML
206
		<link rel='dns-prefetch' href='//s.pubmine.com' />
207
		<link rel='dns-prefetch' href='//x.bidswitch.net' />
208
		<link rel='dns-prefetch' href='//static.criteo.net' />
209
		<link rel='dns-prefetch' href='//ib.adnxs.com' />
210
		<link rel='dns-prefetch' href='//aax.amazon-adsystem.com' />
211
		<link rel='dns-prefetch' href='//bidder.criteo.com' />
212
		<link rel='dns-prefetch' href='//cas.criteo.com' />
213
		<link rel='dns-prefetch' href='//gum.criteo.com' />
214
		<link rel='dns-prefetch' href='//ads.pubmatic.com' />
215
		<link rel='dns-prefetch' href='//gads.pubmatic.com' />
216
		<link rel='dns-prefetch' href='//tpc.googlesyndication.com' />
217
		<link rel='dns-prefetch' href='//ad.doubleclick.net' />
218
		<link rel='dns-prefetch' href='//googleads.g.doubleclick.net' />
219
		<link rel='dns-prefetch' href='//www.googletagservices.com' />
220
		<link rel='dns-prefetch' href='//cdn.switchadhub.com' />
221
		<link rel='dns-prefetch' href='//delivery.g.switchadhub.com' />
222
		<link rel='dns-prefetch' href='//delivery.swid.switchadhub.com' />
223
		<script$data_tags async type="text/javascript" src="//s.pubmine.com/head.js"></script>
224
HTML;
225
	}
226
227
	/**
228
	 * Insert the ad onto the page
229
	 *
230
	 * @since 4.5.0
231
	 */
232
	function insert_ad( $content ) {
233
		// Ad JS won't work in XML feeds.
234
		if ( is_feed() ) {
235
			return $content;
236
		}
237
		/**
238
		 * Allow third-party tools to disable the display of in post ads.
239
		 *
240
		 * @module wordads
241
		 *
242
		 * @since 4.5.0
243
		 *
244
		 * @param bool true Should the in post unit be disabled. Default to false.
245
		 */
246
		$disable = apply_filters( 'wordads_inpost_disable', false );
247
		if ( ! $this->params->should_show() || $disable ) {
248
			return $content;
249
		}
250
251
		$ad_type = $this->option( 'wordads_house' ) ? 'house' : 'iponweb';
252
		return $content . $this->get_ad( 'belowpost', $ad_type );
253
	}
254
255
	/**
256
	 * Inserts ad into header
257
	 *
258
	 * @since 4.5.0
259
	 */
260
	function insert_header_ad() {
261
		/**
262
		 * Allow third-party tools to disable the display of header ads.
263
		 *
264
		 * @module wordads
265
		 *
266
		 * @since 4.5.0
267
		 *
268
		 * @param bool true Should the header unit be disabled. Default to false.
269
		 */
270
		if ( apply_filters( 'wordads_header_disable', false ) ) {
271
			return;
272
		}
273
274
		$ad_type = $this->option( 'wordads_house' ) ? 'house' : 'iponweb';
275
		echo $this->get_ad( 'top', $ad_type );
276
	}
277
278
	/**
279
	 * Special cases for inserting header unit via jQuery
280
	 *
281
	 * @since 4.5.0
282
	 */
283
	function insert_header_ad_special() {
284
		/**
285
		 * Allow third-party tools to disable the display of header ads.
286
		 *
287
		 * @module wordads
288
		 *
289
		 * @since 4.5.0
290
		 *
291
		 * @param bool true Should the header unit be disabled. Default to false.
292
		 */
293
		if ( apply_filters( 'wordads_header_disable', false ) ) {
294
			return;
295
		}
296
297
		$selector = '#content';
298
		switch ( get_stylesheet() ) {
299
			case 'twentyseventeen':
300
				$selector = '#content';
301
				break;
302
			case 'twentyfifteen':
303
				$selector = '#main';
304
				break;
305
			case 'twentyfourteen':
306
				$selector = 'article:first';
307
				break;
308
		}
309
310
		$ad_type = $this->option( 'wordads_house' ) ? 'house' : 'iponweb';
311
		echo $this->get_ad( 'top', $ad_type );
312
		echo <<<HTML
313
		<script type="text/javascript">
314
			jQuery('.wpcnt-header').insertBefore('$selector');
315
		</script>
316
HTML;
317
	}
318
319
	/**
320
	 * Get the ad for the spot and type.
321
	 * @param  string $spot top, side, or belowpost
322
	 * @param  string $type iponweb or adsense
323
	 */
324
	function get_ad( $spot, $type = 'iponweb' ) {
325
		$snippet = '';
326
		$blocker_unit = 'mrec';
0 ignored issues
show
Unused Code introduced by
$blocker_unit 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...
327
		if ( 'iponweb' == $type ) {
328
			// Default to mrec
329
			$width = 300;
330
			$height = 250;
331
332
			$section_id = WORDADS_API_TEST_ID;
0 ignored issues
show
Unused Code introduced by
$section_id 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...
333
			$second_belowpost = '';
0 ignored issues
show
Unused Code introduced by
$second_belowpost 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...
334
			$snippet = '';
335
			if ( 'top' == $spot ) {
336
				// Switch to leaderboard on desktop
337
				if ( ! $this->params->mobile_device ) {
338
					$width = 728;
339
					$height = 90;
340
				}
341
342
				$section_id     = 0 === $this->params->blog_id  ? WORDADS_API_TEST_ID   : $this->params->blog_id . '2';
343
				$blocker_unit   = $this->params->mobile_device  ? 'top_mrec'            : 'top';
344
				$snippet        = $this->get_ad_snippet( $section_id, $height, $width, $blocker_unit );
345
346
			} else if ( 'belowpost' == $spot ) {
347
				$section_id     = 0 === $this->params->blog_id	? WORDADS_API_TEST_ID   : $this->params->blog_id . '1';
348
				$snippet = $this->get_ad_snippet( $section_id, $height, $width, 'mrec', 'float:left;margin-right:5px;margin-top:0px;' );
349
				$width = 300;
350
				$height = 250;
351
352
				if ( $this->option( 'wordads_second_belowpost', true ) ) {
353
					$section_id2 = 0 === $this->params->blog_id ? WORDADS_API_TEST_ID2 : $this->params->blog_id . '4';
354
					$snippet .= $this->get_ad_snippet( $section_id2, $height, $width, 'mrec2', 'float:left;margin-top:0px;' );
355
				}
356
			}
357
		} else if ( 'house' == $type ) {
358
			$leaderboard = 'top' == $spot && ! $this->params->mobile_device;
359
			$snippet = $this->get_house_ad( $leaderboard ? 'leaderboard' : 'mrec' );
360
			if ( 'belowpost' == $spot && $this->option( 'wordads_second_belowpost', true ) ) {
361
				$snippet .= $this->get_house_ad( $leaderboard ? 'leaderboard' : 'mrec' );
362
			}
363
		}
364
365
		$header = 'top' == $spot ? 'wpcnt-header' : '';
366
		$about = __( 'Advertisements', 'jetpack' );
367
		return <<<HTML
368
		<div class="wpcnt $header">
369
			<div class="wpa">
370
				<span class="wpa-about">$about</span>
371
				<div class="u $spot">
372
					$snippet
373
				</div>
374
			</div>
375
		</div>
376
HTML;
377
	}
378
379
380
	/**
381
	 * Returns the snippet to be inserted into the ad unit
382
	 * @param  int $section_id
383
	 * @param  int $height
384
	 * @param  int $width
385
	 * @param  string $css
386
	 * @return string
387
	 *
388
	 * @since 5.7
389
	 */
390
	function get_ad_snippet( $section_id, $height, $width, $adblock_unit = 'mrec', $css = '' ) {
391
		$this->ads[] = array( 'id' => $section_id, 'width' => $width, 'height' => $height );
0 ignored issues
show
Bug introduced by
The property ads does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
392
		$data_tags = $this->params->cloudflare ? ' data-cfasync="false"' : '';
393
		$adblock_ad = $this->get_adblocker_ad( $adblock_unit );
394
395
		return <<<HTML
396
		<div style="padding-bottom:15px;width:{$width}px;height:{$height}px;$css">
397
			<div id="atatags-{$section_id}">
398
				<script$data_tags type="text/javascript">
399
				__ATA.cmd.push(function() {
400
					__ATA.initSlot('atatags-{$section_id}',  {
401
						collapseEmpty: 'before',
402
						sectionId: '{$section_id}',
403
						width: {$width},
404
						height: {$height}
405
					});
406
				});
407
				</script>
408
				$adblock_ad
409
			</div>
410
		</div>
411
HTML;
412
	}
413
414
	/**
415
	 * Get Criteo Acceptable Ad unit
416
	 * @param  string $unit mrec, mrec2, widesky, top, top_mrec
417
	 *
418
	 * @since 5.3
419
	 */
420
	public function get_adblocker_ad( $unit = 'mrec' ) {
421
		$data_tags = $this->params->cloudflare ? ' data-cfasync="false"' : '';
422
		$criteo_id = mt_rand();
423
		$height = 250;
424
		$width = 300;
425
		$zone_id = 388248;
426
		if ( 'mrec2' == $unit ) { // 2nd belowpost
427
			$zone_id = 837497;
428
		} else if ( 'widesky' == $unit ) { // sidebar
429
			$zone_id = 563902;
430
			$width = 160;
431
			$height= 600;
432
		} else if ( 'top' == $unit ) { // top leaderboard
433
			$zone_id = 563903;
434
			$width = 728;
435
			$height = 90;
436
		} else if ( 'top_mrec' == $unit ) { // top mrec
437
			$zone_id = 563903;
438
		}
439
440
		return <<<HTML
441
		<div id="crt-$criteo_id" style="width:{$width}px;height:{$height}px;display:none !important;"></div>
442
		<script$data_tags type="text/javascript">
443
		(function(){var c=function(){var a=document.getElementById("crt-{$criteo_id}");window.Criteo?(a.parentNode.style.setProperty("display","inline-block","important"),a.style.setProperty("display","block","important"),window.Criteo.DisplayAcceptableAdIfAdblocked({zoneid:{$zone_id},containerid:"crt-{$criteo_id}",collapseContainerIfNotAdblocked:!0,callifnotadblocked:function(){a.style.setProperty("display","none","important");a.style.setProperty("visbility","hidden","important")}})):(a.style.setProperty("display","none","important"),a.style.setProperty("visibility","hidden","important"))};if(window.Criteo)c();else{if(!__ATA.criteo.script){var b=document.createElement("script");b.src="//static.criteo.net/js/ld/publishertag.js";b.onload=function(){for(var a=0;a<__ATA.criteo.cmd.length;a++){var b=__ATA.criteo.cmd[a];"function"===typeof b&&b()}};(document.head||document.getElementsByTagName("head")[0]).appendChild(b);__ATA.criteo.script=b}__ATA.criteo.cmd.push(c)}})();
444
		</script>
445
HTML;
446
	}
447
448
	/**
449
	 * Check the reasons to bail before we attempt to insert ads.
450
	 * @return true if we should bail (don't insert ads)
451
	 *
452
	 * @since 4.5.0
453
	 */
454
	public function should_bail() {
455
		return ! $this->option( 'wordads_approved' );
456
	}
457
458
	/**
459
	 * Returns markup for HTML5 house ad base on unit
460
	 * @param  string $unit mrec, widesky, or leaderboard
461
	 * @return string       markup for HTML5 house ad
462
	 *
463
	 * @since 4.7.0
464
	 */
465
	public function get_house_ad( $unit = 'mrec' ) {
466
467
		switch ( $unit ) {
468
			case 'widesky':
469
				$width  = 160;
470
				$height = 600;
471
				break;
472
			case 'leaderboard':
473
				$width  = 728;
474
				$height = 90;
475
				break;
476
			case 'mrec':
477
			default:
478
				$width  = 300;
479
				$height = 250;
480
				break;
481
		}
482
483
		return <<<HTML
484
		<iframe
485
			src="https://s0.wp.com/wp-content/blog-plugins/wordads/house/html5/$unit/index.html"
486
			width="$width"
487
			height="$height"
488
			frameborder="0"
489
			scrolling="no"
490
			marginheight="0"
491
			marginwidth="0">
492
		</iframe>
493
HTML;
494
	}
495
496
	/**
497
	 * Activation hook actions
498
	 *
499
	 * @since 4.5.0
500
	 */
501
	public static function activate() {
502
		WordAds_API::update_wordads_status_from_api();
503
	}
504
}
505
506
add_action( 'jetpack_activate_module_wordads', array( 'WordAds', 'activate' ) );
507
add_action( 'jetpack_activate_module_wordads', array( 'WordAds_Cron', 'activate' ) );
508
add_action( 'jetpack_deactivate_module_wordads', array( 'WordAds_Cron', 'deactivate' ) );
509
510
global $wordads;
511
$wordads = new WordAds();
512