Completed
Push — add/changelog-66 ( 3dd88f...f645f6 )
by Jeremy
27:12 queued 17:45
created

Publicize_UI::wrapper_admin_page()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
* Only user facing pieces of Publicize are found here.
5
*/
6
class Publicize_UI {
7
8
	/**
9
	* Contains an instance of class 'publicize' which loads Keyring, sets up services, etc.
10
	*/
11
	public $publicize;
12
13
	/**
14
	* Hooks into WordPress to display the various pieces of UI and load our assets
15
	*/
16
	function __construct() {
17
		global $publicize;
18
19
		$this->publicize = $publicize = new Publicize;
20
21
		add_action( 'init', array( $this, 'init' ) );
22
	}
23
24
	function init() {
25
		// Show only to users with the capability required to manage their Publicize connections.
26
		/**
27
		 * Filter what user capability is required to use the publicize form on the edit post page. Useful if publish post capability has been removed from role.
28
		 *
29
		 * @module publicize
30
		 *
31
		 * @since 4.1.0
32
		 *
33
		 * @param string $capability User capability needed to use publicize
34
		 */
35
		$capability = apply_filters( 'jetpack_publicize_capability', 'publish_posts' );
36
		if ( ! current_user_can( $capability ) ) {
37
			return;
38
		}
39
40
		// assets (css, js)
41
		add_action( 'load-settings_page_sharing', array( &$this, 'load_assets' ) );
42
		add_action( 'admin_head-post.php', array( &$this, 'post_page_metabox_assets' ) );
43
		add_action( 'admin_head-post-new.php', array( &$this, 'post_page_metabox_assets' ) );
44
45
		// management of publicize (sharing screen, ajax/lightbox popup, and metabox on post screen)
46
		add_action( 'pre_admin_screen_sharing', array( &$this, 'admin_page' ) );
47
		add_action( 'post_submitbox_misc_actions', array( &$this, 'post_page_metabox' ) );
48
	}
49
50
	/**
51
	* If the ShareDaddy plugin is not active we need to add the sharing settings page to the menu still
52
	*/
53
	function sharing_menu() {
54
		add_submenu_page(
55
			'options-general.php',
56
			__( 'Sharing Settings', 'jetpack' ),
57
			__( 'Sharing', 'jetpack' ),
58
			'publish_posts',
59
			'sharing',
60
			array( &$this, 'wrapper_admin_page' )
61
		);
62
	}
63
64
	function wrapper_admin_page() {
65
		Jetpack_Admin_Page::wrap_ui( array( &$this, 'management_page' ), array( 'is-wide' => true ) );
66
	}
67
	/**
68
	* Management page to load if Sharedaddy is not active so the 'pre_admin_screen_sharing' action exists.
69
	*/
70
	function management_page() { ?>
71
		<div class="wrap">
72
			<div class="icon32" id="icon-options-general"><br /></div>
73
			<h1><?php _e( 'Sharing Settings', 'jetpack' ); ?></h1>
74
75
				<?php
76
				/** This action is documented in modules/sharedaddy/sharing.php */
77
				do_action( 'pre_admin_screen_sharing' );
78
				?>
79
80
		</div> <?php
81
	}
82
83
	/**
84
	* styling for the sharing screen and popups
85
	* JS for the options and switching
86
	*/
87
	function load_assets() {
88
		wp_enqueue_script(
89
			'publicize',
90
			Jetpack::get_file_url_for_environment(
91
				'_inc/build/publicize/assets/publicize.min.js',
92
				'modules/publicize/assets/publicize.js'
93
			),
94
			array( 'jquery', 'thickbox' ),
95
			'20121019'
96
		);
97
		if ( is_rtl() ) {
98
			wp_enqueue_style( 'publicize', plugins_url( 'assets/rtl/publicize-rtl.css', __FILE__ ), array(), '20180301' );
99
		} else {
100
			wp_enqueue_style( 'publicize', plugins_url( 'assets/publicize.css', __FILE__ ), array(), '20180301' );
101
		}
102
103
		Jetpack_Admin_Page::load_wrapper_styles();
104
		wp_enqueue_style( 'social-logos' );
105
106
		add_thickbox();
107
	}
108
109
	public static function connected_notice( $service_name ) { ?>
110
		<div class='updated'>
111
			<p><?php
112
113
			if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
114
				$platform =  'WordPress.com';
115
			} else {
116
				$platform = 'Jetpack';
117
			}
118
119
			printf(
120
				__( 'You have successfully connected your %1$s account with %2$s.', '1: Service Name (Facebook, Twitter, ...), 2. WordPress.com or Jetpack', 'jetpack' ),
121
				Publicize::get_service_label( $service_name ),
122
				$platform
123
			); ?></p>
124
		</div><?php
125
	}
126
127
	public static function denied_notice() { ?>
128
		<div class='updated'>
129
			<p><?php _e ( "You have chosen not to connect your blog. Please click 'accept' when prompted if you wish to connect your accounts.", 'jetpack' ); ?></p>
130
		</div><?php
131
	}
132
133
	/**
134
	* Lists the current user's publicized accounts for the blog
135
	* looks exactly like Publicize v1 for now, UI and functionality updates will come after the move to keyring
136
	*/
137
	function admin_page() {
138
		$_blog_id = get_current_blog_id();
139
		?>
140
141
		<form action="" id="publicize-form">
142
			<h2 id="publicize"><?php _e( 'Publicize', 'jetpack' ) ?></h2>
143
144
			<?php
145
				if ( ! empty( $_GET['action'] ) && 'deny' == $_GET['action'] ) {
146
					$this->denied_notice();
147
				}
148
			?>
149
150
			<p>
151
				<?php esc_html_e( 'Connect your blog to popular social networking sites and automatically share new posts with your friends.', 'jetpack' ) ?>
152
				<?php esc_html_e( 'You can make a connection for just yourself or for all users on your blog. Shared connections are marked with the (Shared) text.', 'jetpack' ); ?>
153
			</p>
154
155
			<?php
156
			if ( $this->in_jetpack ) {
0 ignored issues
show
Bug introduced by
The property in_jetpack 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...
157
				$doc_link = "http://jetpack.com/support/publicize/";
158
			} else {
159
				$doc_link = "http://en.support.wordpress.com/publicize/";
160
			}
161
			?>
162
163
			<p>&rarr; <a href="<?php echo esc_url( $doc_link ); ?>" rel="noopener noreferrer" target="_blank"><?php esc_html_e( 'More information on using Publicize.', 'jetpack' ); ?></a></p>
164
165
			<div id="publicize-services-block">
166
				<?php
167
				$services = $this->publicize->get_services( 'all' );
168
				$total_num_of_services = count ( $services );
169
				$service_num = 0;?>
170
171
				<div class='left'>
172
173
				<?php
174
				foreach ( $services as $name => $service ) :
175
					$connect_url = $this->publicize->connect_url( $name );
176
					if ( $service_num == ( round ( ( $total_num_of_services / 2 ), 0 ) ) )
177
						echo "</div><div class='right'>";
178
					$service_num++;
179
					?>
180
					<div class="publicize-service-entry" <?php if ( $service_num > 0 ): ?>class="connected"<?php endif; ?> >
181
						<div id="<?php echo esc_attr( $name ); ?>" class="publicize-service-left">
182
							<a href="<?php echo esc_url( $connect_url ); ?>" id="service-link-<?php echo esc_attr( $name ); ?>" target="_top"><?php echo $this->publicize->get_service_label( $name ); ?></a>
183
						</div>
184
185
186
						<div class="publicize-service-right">
187
							<?php if ( $this->publicize->is_enabled( $name ) && $connections = $this->publicize->get_connections( $name ) ) : ?>
188
								<ul>
189
									<?php
190
									foreach( $connections as $c ) :
191
										$id = $this->publicize->get_connection_id( $c );
192
										$disconnect_url = $this->publicize->disconnect_url( $name, $id );
193
194
										$cmeta = $this->publicize->get_connection_meta( $c );
195
										$profile_link = $this->publicize->get_profile_link( $name, $c );
196
										$connection_display = $this->publicize->get_display_name( $name, $c );
197
198
										$options_nonce = wp_create_nonce( 'options_page_' . $name . '_' . $id ); ?>
199
200
										<?php if ( $this->publicize->show_options_popup( $name, $c ) ): ?>
201
										<script type="text/javascript">
202
										jQuery(document).ready( function($) {
203
											showOptionsPage.call(
204
											this,
205
											'<?php echo esc_js( $name ); ?>',
206
											'<?php echo esc_js( $options_nonce ); ?>',
207
											'<?php echo esc_js( $id ); ?>'
208
											);
209
										} );
210
										</script>
211
										<?php endif; ?>
212
213
										<li class="publicize-connection" data-connection-id="<?php echo esc_attr( $id ); ?>">
214
											<?php esc_html_e( 'Connected as:', 'jetpack' ); ?>
215
											<?php
216
											if ( !empty( $profile_link ) ) : ?>
217
												<a class="publicize-profile-link" href="<?php echo esc_url( $profile_link ); ?>" target="_top">
218
													<?php echo esc_html( $connection_display ); ?>
219
												</a><?php
220
											else :
221
												echo esc_html( $connection_display );
222
											endif;
223
											?>
224
225
											<?php if ( 0 == $cmeta['connection_data']['user_id'] ) : ?>
226
												<small>(<?php esc_html_e( 'Shared', 'jetpack' ); ?>)</small>
227
228
												<?php if ( current_user_can( $this->publicize->GLOBAL_CAP ) ) : ?>
229
													<a class="pub-disconnect-button" title="<?php esc_html_e( 'Disconnect', 'jetpack' ); ?>" href="<?php echo esc_url( $disconnect_url ); ?>" target="_top">×</a>
230
												<?php endif; ?>
231
232
											<?php else : ?>
233
												<a class="pub-disconnect-button" title="<?php esc_html_e( 'Disconnect', 'jetpack' ); ?>" href="<?php echo esc_url( $disconnect_url ); ?>" target="_top">×</a>
234
											<?php endif; ?>
235
236
											<br/>
237
											<div class="pub-connection-test test-in-progress" id="pub-connection-test-<?php echo esc_attr( $id ); ?>" >
238
											</div>
239
										</li>
240
241
										<?php
242
									endforeach;
243
									?>
244
								</ul>
245
							<?php endif; ?>
246
247
248
249
							<?php
250
								$connections = $this->publicize->get_connections( $name );
251
								if ( empty ( $connections ) ) { ?>
252
									<a id="<?php echo esc_attr( $name ); ?>" class="publicize-add-connection button" href="<?php echo esc_url( $connect_url ); ?>" target="_top"><?php echo esc_html( __( 'Connect', 'jetpack' ) ); ?></a>
253
								<?php } else { ?>
254
									<a id="<?php echo esc_attr( $name ); ?>" class="publicize-add-connection button add-new" href="<?php echo esc_url( $connect_url ); ?>" target="_top"><?php echo esc_html( __( 'Add New', 'jetpack' ) ); ?></a>
255
			  					<?php } ?>
256
			  			</div>
257
			  		</div>
258
				<?php endforeach; ?>
259
				</div>
260
				<script>
261
				(function($){
262
					$('.pub-disconnect-button').on('click', function(e){ if ( confirm( '<?php echo esc_js( __( 'Are you sure you want to stop Publicizing posts to this connection?', 'jetpack' ) ); ?>' ) ) {
263
								return true;
264
							} else {
265
							e.preventDefault();
266
							return false;
267
						}
268
					})
269
				})(jQuery);
270
				</script>
271
			</div>
272
273
			<?php wp_nonce_field( "wpas_posts_{$_blog_id}", "_wpas_posts_{$_blog_id}_nonce" ); ?>
274
			<input type="hidden" id="wpas_ajax_blog_id" name="wpas_ajax_blog_id" value="<?php echo $_blog_id; ?>" />
275
		</form><?php
276
277
	}
278
279
	public static function global_checkbox( $service_name, $id ) {
280
		global $publicize;
281
		if ( current_user_can( $publicize->GLOBAL_CAP ) ) : ?>
282
			<p>
283
				<input id="globalize_<?php echo $service_name; ?>" type="checkbox" name="global" value="<?php echo wp_create_nonce( 'publicize-globalize-' . $id ) ?>" />
284
				<label for="globalize_<?php echo $service_name; ?>"><?php _e( 'Make this connection available to all users of this blog?', 'jetpack' ); ?></label>
285
			</p>
286
		<?php endif;
287
	}
288
289
	function broken_connection( $service_name, $id ) { ?>
290
		<div id="thickbox-content">
291
			<div class='error'>
292
				<p><?php printf( __( 'There was a problem connecting to %s. Please disconnect and try again.', 'jetpack' ), Publicize::get_service_label( $service_name ) ); ?></p>
293
			</div>
294
		</div><?php
295
	}
296
297
	public static function options_page_other( $service_name ) {
298
		// Nonce check
299
		check_admin_referer( "options_page_{$service_name}_" . $_REQUEST['connection'] );
300
		?>
301
		<div id="thickbox-content">
302
			<?php
303
			ob_start();
304
			Publicize_UI::connected_notice( $service_name );
305
			$update_notice = ob_get_clean();
306
			if ( ! empty( $update_notice ) )
307
				echo $update_notice;
308
			?>
309
310
			<?php Publicize_UI::global_checkbox( $service_name, $_REQUEST['connection'] ); ?>
311
312
			<p style="text-align: center;">
313
				<input type="submit" value="<?php esc_attr_e( 'OK', 'jetpack' ) ?>" class="button <?php echo $service_name; ?>-options save-options" name="save" data-connection="<?php echo esc_attr( $_REQUEST['connection'] ); ?>" rel="<?php echo wp_create_nonce( 'save_'.$service_name.'_token_' . $_REQUEST['connection'] ) ?>" />
314
			</p> <br />
315
		</div>
316
		<?php
317
	}
318
319
	/**
320
	* CSS for styling the publicize message box and counter that displays on the post page.
321
	* There is also some JavaScript for length counting and some basic display effects.
322
	*/
323
	function post_page_metabox_assets() {
324
		global $post;
325
		$user_id = empty( $post->post_author ) ? $GLOBALS['user_ID'] : $post->post_author;
0 ignored issues
show
Unused Code introduced by
$user_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...
326
327
		$default_prefix = $this->publicize->default_prefix;
328
		$default_prefix = preg_replace( '/%([0-9])\$s/', "' + %\\1\$s + '", esc_js( $default_prefix ) );
329
330
		$default_message = $this->publicize->default_message;
331
		$default_message = preg_replace( '/%([0-9])\$s/', "' + %\\1\$s + '", esc_js( $default_message ) );
332
333
		$default_suffix = $this->publicize->default_suffix;
334
		$default_suffix = preg_replace( '/%([0-9])\$s/', "' + %\\1\$s + '", esc_js( $default_suffix ) ); ?>
335
336
<script type="text/javascript">
337
jQuery( function($) {
338
	var wpasTitleCounter    = $( '#wpas-title-counter' ),
339
		wpasTwitterCheckbox = $( '.wpas-submit-twitter' ).length,
340
		wpasTitle = $('#wpas-title').keyup( function() {
341
		var length = wpasTitle.val().length;
342
		wpasTitleCounter.text( length );
343
		if ( wpasTwitterCheckbox && length > 256 ) {
344
			wpasTitleCounter.addClass( 'wpas-twitter-length-limit' );
345
		} else {
346
			wpasTitleCounter.removeClass( 'wpas-twitter-length-limit' );
347
		}
348
		} ),
349
		authClick = false;
350
351
	$('#publicize-disconnected-form-show').click( function() {
352
		$('#publicize-form').slideDown( 'fast' );
353
		$(this).hide();
354
	} );
355
356
	$('#publicize-disconnected-form-hide').click( function() {
357
		$('#publicize-form').slideUp( 'fast' );
358
		$('#publicize-disconnected-form-show').show();
359
	} );
360
361
	$('#publicize-form-edit').click( function() {
362
		$('#publicize-form').slideDown( 'fast', function() {
363
			wpasTitle.focus();
364
			if ( !wpasTitle.text() ) {
365
				var url = $('#shortlink').length ? $('#shortlink').val() : '';
366
367
				var defaultMessage = $.trim( '<?php printf( $default_prefix, 'url' ); printf( $default_message, '$("#title").val()', 'url' ); printf( $default_suffix, 'url' ); ?>' );
368
369
				wpasTitle.append( defaultMessage.replace( /<[^>]+>/g,'') );
370
371
				var selBeg = defaultMessage.indexOf( $("#title").val() );
372
				if ( selBeg < 0 ) {
373
					selBeg = 0;
374
					selEnd = 0;
375
				} else {
376
					selEnd = selBeg + $("#title").val().length;
377
				}
378
379
				var domObj = wpasTitle.get(0);
380
				if ( domObj.setSelectionRange ) {
381
					domObj.setSelectionRange( selBeg, selEnd );
382
				} else if ( domObj.createTextRange ) {
383
					var r = domObj.createTextRange();
384
					r.moveStart( 'character', selBeg );
385
					r.moveEnd( 'character', selEnd );
386
					r.select();
387
				}
388
			}
389
			wpasTitle.keyup();
390
		} );
391
		$('#publicize-defaults').hide();
392
		$(this).hide();
393
		return false;
394
	} );
395
396
	$('#publicize-form-hide').click( function() {
397
		var newList = $.map( $('#publicize-form').slideUp( 'fast' ).find( ':checked' ), function( el ) {
398
			return $.trim( $(el).parent( 'label' ).text() );
399
		} );
400
		$('#publicize-defaults').html( '<strong>' + newList.join( '</strong>, <strong>' ) + '</strong>' ).show();
401
		$('#publicize-form-edit').show();
402
		return false;
403
	} );
404
405
	$('.authorize-link').click( function() {
406
		if ( authClick ) {
407
			return false;
408
		}
409
		authClick = true;
410
		$(this).after( '<img src="images/loading.gif" class="alignleft" style="margin: 0 .5em" />' );
411
		$.ajaxSetup( { async: false } );
412
413
		if ( window.wp && window.wp.autosave ) {
414
			window.wp.autosave.server.triggerSave();
415
		} else {
416
			autosave();
417
		}
418
419
		return true;
420
	} );
421
422
	$( '.pub-service' ).click( function() {
423
		var service = $(this).data( 'service' ),
424
			fakebox = '<input id="wpas-submit-' + service + '" type="hidden" value="1" name="wpas[submit][' + service + ']" />';
425
		$( '#add-publicize-check' ).append( fakebox );
426
	} );
427
428
	publicizeConnTestStart = function() {
429
		$( '#pub-connection-tests' )
430
			.removeClass( 'below-h2' )
431
			.removeClass( 'error' )
432
			.removeClass( 'publicize-token-refresh-message' )
433
			.addClass( 'test-in-progress' )
434
			.html( '' );
435
		$.post( ajaxurl, { action: 'test_publicize_conns' }, publicizeConnTestComplete );
436
	}
437
438
	publicizeConnRefreshClick = function( event ) {
439
		event.preventDefault();
440
		var popupURL = event.currentTarget.href;
441
		var popupTitle = event.currentTarget.title;
442
		// open a popup window
443
		// when it is closed, kick off the tests again
444
		var popupWin = window.open( popupURL, popupTitle, '' );
445
		var popupWinTimer= window.setInterval( function() {
446
			if ( popupWin.closed !== false ) {
447
				window.clearInterval( popupWinTimer );
448
				publicizeConnTestStart();
449
			}
450
		}, 500 );
451
	}
452
453
	publicizeConnTestComplete = function( response ) {
454
		var testsSelector = $( '#pub-connection-tests' );
455
		testsSelector
456
			.removeClass( 'test-in-progress' )
457
			.removeClass( 'below-h2' )
458
			.removeClass( 'error' )
459
			.removeClass( 'publicize-token-refresh-message' )
460
			.html( '' );
461
462
		// If any of the tests failed, show some stuff
463
		var somethingShownAlready = false;
464
		var facebookNotice = false;
465
		$.each( response.data, function( index, testResult ) {
466
467
			// find the li for this connection
468
			if ( ! testResult.connectionTestPassed && testResult.userCanRefresh ) {
469
				if ( ! somethingShownAlready ) {
470
					testsSelector
471
						.addClass( 'below-h2' )
472
						.addClass( 'error' )
473
						.addClass( 'publicize-token-refresh-message' )
474
						.append( "<p><?php echo esc_html( __( 'Before you hit Publish, please refresh the following connection(s) to make sure we can Publicize your post:', 'jetpack' ) ); ?></p>" );
475
					somethingShownAlready = true;
476
				}
477
478
				if ( testResult.userCanRefresh ) {
479
					testsSelector.append( '<p/>' );
480
					$( '<a/>', {
481
						'class'  : 'pub-refresh-button button',
482
						'title'  : testResult.refreshText,
483
						'href'   : testResult.refreshURL,
484
						'text'   : testResult.refreshText,
485
						'target' : '_refresh_' + testResult.serviceName
486
					} )
487
						.appendTo( testsSelector.children().last() )
488
						.click( publicizeConnRefreshClick );
489
				}
490
			}
491
492
			if( ! testResult.connectionTestPassed && ! testResult.userCanRefresh ) {
493
494
				$( '#wpas-submit-' + testResult.unique_id ).prop( "checked", false ).prop( "disabled", true );
495
				if ( ! facebookNotice ) {
496
					var message = '<p>'
497
						+ testResult.connectionTestMessage
498
						+ '</p><p>'
499
						+ ' <a class="button" href="<?php echo esc_url( admin_url( 'options-general.php?page=sharing' ) ); ?>" rel="noopener noreferrer" target="_blank">'
500
						+ '<?php echo esc_html( __( 'Update Your Sharing Settings' ,'jetpack' ) ); ?>'
501
						+ '</a>'
502
						+ '<p>';
503
504
					testsSelector
505
						.addClass( 'below-h2' )
506
						.addClass( 'error' )
507
						.addClass( 'publicize-token-refresh-message' )
508
						.append( message );
509
					facebookNotice = true;
510
				}
511
512
			}
513
514
515
		} );
516
	}
517
518
	$( document ).ready( function() {
519
		// If we have the #pub-connection-tests div present, kick off the connection test
520
		if ( $( '#pub-connection-tests' ).length ) {
521
			publicizeConnTestStart();
522
		}
523
	} );
524
525
} );
526
</script>
527
528
<style type="text/css">
529
#publicize {
530
	line-height: 1.5;
531
}
532
#publicize ul {
533
	margin: 4px 0 4px 6px;
534
}
535
#publicize li {
536
	margin: 0;
537
}
538
#publicize textarea {
539
	margin: 4px 0 0;
540
	width: 100%
541
}
542
#publicize ul.not-connected {
543
	list-style: square;
544
	padding-left: 1em;
545
}
546
#publicize-title:before {
547
	content: "\f237";
548
	font: normal 20px/1 dashicons;
549
	speak: none;
550
	margin-left: -1px;
551
	padding-right: 3px;
552
	vertical-align: top;
553
	-webkit-font-smoothing: antialiased;
554
	color: #82878c;
555
}
556
.post-new-php .authorize-link, .post-php .authorize-link {
557
	line-height: 1.5em;
558
}
559
.post-new-php .authorize-message, .post-php .authorize-message {
560
	margin-bottom: 0;
561
}
562
#poststuff #publicize .updated p {
563
	margin: .5em 0;
564
}
565
.wpas-twitter-length-limit {
566
	color: red;
567
}
568
</style><?php
569
	}
570
571
	/**
572
	* Controls the metabox that is displayed on the post page
573
	* Allows the user to customize the message that will be sent out to the social network, as well as pick which
574
	* networks to publish to. Also displays the character counter and some other information.
575
	*/
576
	function post_page_metabox() {
577
		global $post;
578
579
		if ( ! $this->publicize->post_type_is_publicizeable( $post->post_type ) )
580
			return;
581
582
		$user_id = empty( $post->post_author ) ? $GLOBALS['user_ID'] : $post->post_author;
0 ignored issues
show
Unused Code introduced by
$user_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...
583
		$services = $this->publicize->get_services( 'connected' );
584
		$available_services = $this->publicize->get_services( 'all' );
585
586
		if ( ! is_array( $available_services ) )
587
			$available_services = array();
588
589
		if ( ! is_array( $services ) )
590
			$services = array();
591
		?>
592
		<div id="publicize" class="misc-pub-section misc-pub-section-last">
593
			<span id="publicize-title">
594
				<?php esc_html_e( 'Publicize:', 'jetpack' ); ?>
595
				<?php if ( 0 < count( $services ) ) : ?>
596
					<?php list( $publicize_form, $active ) = $this->get_metabox_form_connected( $services ); ?>
597
					<span id="publicize-defaults">
598
						<?php foreach ( $active as $item ) : ?>
599
							<strong><?php echo esc_html( $item ); ?></strong>
600
						<?php endforeach; ?>
601
					</span>
602
					<a href="#" id="publicize-form-edit"><?php esc_html_e( 'Edit', 'jetpack' ); ?></a>&nbsp;<a href="<?php echo esc_url( admin_url( 'options-general.php?page=sharing' ) ); ?>" rel="noopener noreferrer" target="_blank"><?php _e( 'Settings', 'jetpack' ); ?></a><br />
603
				<?php else : ?>
604
					<?php $publicize_form = $this->get_metabox_form_disconnected( $available_services ); ?>
605
					<strong><?php echo __( 'Not Connected', 'jetpack' ); ?></strong>
606
					<a href="#" id="publicize-disconnected-form-show"><?php esc_html_e( 'Edit', 'jetpack' ); ?></a><br />
607
				<?php endif; ?>
608
			</span>
609
			<?php
610
			/**
611
			 * Filter the Publicize details form.
612
			 *
613
			 * @module publicize
614
			 *
615
			 * @since 2.0.0
616
			 *
617
			 * @param string $publicize_form Publicize Details form appearing above Publish button in the editor.
618
			 */
619
			echo apply_filters( 'publicize_form', $publicize_form );
620
			?>
621
		</div> <?php // #publicize
622
	}
623
624
	private function get_metabox_form_connected( $services ) {
625
		global $post;
626
		$active = array();
627
		ob_start();
628
		?> <div id="publicize-form" class="hide-if-js">
629
			<ul>
630
631
			<?php
632
			// We can set an _all flag to indicate that this post is completely done as
633
			// far as Publicize is concerned. Jetpack uses this approach. All published posts in Jetpack
634
			// have Publicize disabled.
635
			$all_done = get_post_meta( $post->ID, $this->publicize->POST_DONE . 'all', true ) || ( $this->in_jetpack && 'publish' == $post->post_status );
636
637
			// We don't allow Publicizing to the same external id twice, to prevent spam
638
			$service_id_done = (array) get_post_meta( $post->ID, $this->publicize->POST_SERVICE_DONE, true );
639
640
			foreach ( $services as $name => $connections ) {
641
				foreach ( $connections as $connection ) {
642
					$connection_data = '';
643 View Code Duplication
					if ( method_exists( $connection, 'get_meta' ) )
644
						$connection_data = $connection->get_meta( 'connection_data' );
645
					elseif ( ! empty( $connection['connection_data'] ) )
646
						$connection_data = $connection['connection_data'];
647
648
					/**
649
					 * Filter whether a post should be publicized to a given service.
650
					 *
651
					 * @module publicize
652
					 *
653
					 * @since 2.0.0
654
					 *
655
					 * @param bool true Should the post be publicized to a given service? Default to true.
656
					 * @param int $post->ID Post ID.
657
					 * @param string $name Service name.
658
					 * @param array $connection_data Array of information about all Publicize details for the site.
659
					 */
660
					if ( ! $continue = apply_filters( 'wpas_submit_post?', true, $post->ID, $name, $connection_data ) ) {
661
						continue;
662
					}
663
664 View Code Duplication
					if ( ! empty( $connection->unique_id ) ) {
665
						$unique_id = $connection->unique_id;
666
					} else if ( ! empty( $connection['connection_data']['token_id'] ) ) {
667
						$unique_id = $connection['connection_data']['token_id'];
668
					}
669
670
					// Should we be skipping this one?
671
					$skip = (
672
						(
673
							in_array( $post->post_status, array( 'publish', 'draft', 'future' ) )
674
							&&
675
							get_post_meta( $post->ID, $this->publicize->POST_SKIP . $unique_id, true )
0 ignored issues
show
Bug introduced by
The variable $unique_id 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...
676
						)
677
						||
678
						(
679
							is_array( $connection )
680
							&&
681
							(
682
								( isset( $connection['meta']['external_id'] ) && ! empty( $service_id_done[ $name ][ $connection['meta']['external_id'] ] ) )
683
								||
684
								// Jetpack's connection data looks a little different.
685
								( isset( $connection['external_id'] ) && ! empty( $service_id_done[ $name ][ $connection['external_id'] ] ) )
686
							)
687
						)
688
					);
689
690
					// Was this connections (OR, old-format service) already Publicized to?
691
					$done = ( 1 == get_post_meta( $post->ID, $this->publicize->POST_DONE . $unique_id, true ) ||  1 == get_post_meta( $post->ID, $this->publicize->POST_DONE . $name, true ) ); // New and old style flags
692
693
					// If this one has already been publicized to, don't let it happen again
694
					$disabled = '';
0 ignored issues
show
Unused Code introduced by
$disabled 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...
695
					if ( $done ) {
696
						$disabled = ' disabled="disabled"';
0 ignored issues
show
Unused Code introduced by
$disabled 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...
697
					}
698
699
					// If this is a global connection and this user doesn't have enough permissions to modify
700
					// those connections, don't let them change it
701
					$cmeta = $this->publicize->get_connection_meta( $connection );
702
					$hidden_checkbox = false;
703
					if ( !$done && ( 0 == $cmeta['connection_data']['user_id'] && !current_user_can( $this->publicize->GLOBAL_CAP ) ) ) {
704
						$disabled = ' disabled="disabled"';
0 ignored issues
show
Unused Code introduced by
$disabled 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...
705
						/**
706
						 * Filters the checkboxes for global connections with non-prilvedged users.
707
						 *
708
						 * @module publicize
709
						 *
710
						 * @since 3.7.0
711
						 *
712
						 * @param bool   $checked Indicates if this connection should be enabled. Default true.
713
						 * @param int    $post->ID ID of the current post
714
						 * @param string $name Name of the connection (Facebook, Twitter, etc)
715
						 * @param array  $connection Array of data about the connection.
716
						 */
717
						$hidden_checkbox = apply_filters( 'publicize_checkbox_global_default', true, $post->ID, $name, $connection );
718
					}
719
720
					// Determine the state of the checkbox (on/off) and allow filtering
721
					$checked = $skip != 1 || $done;
722
					/**
723
					 * Filter the checkbox state of each Publicize connection appearing in the post editor.
724
					 *
725
					 * @module publicize
726
					 *
727
					 * @since 2.0.1
728
					 *
729
					 * @param bool $checked Should the Publicize checkbox be enabled for a given service.
730
					 * @param int $post->ID Post ID.
731
					 * @param string $name Service name.
732
					 * @param array $connection Array of connection details.
733
					 */
734
					$checked = apply_filters( 'publicize_checkbox_default', $checked, $post->ID, $name, $connection );
735
736
					// Force the checkbox to be checked if the post was DONE, regardless of what the filter does
737
					if ( $done ) {
738
						$checked = true;
739
					}
740
					$disabled = false;
741
					// This post has been handled, so disable everything
742
					if ( $all_done ) {
743
						$disabled = ' disabled="disabled"';
744
					}
745
746
					$label = sprintf(
747
						_x( '%1$s: %2$s', 'Service: Account connected as', 'jetpack' ),
748
						esc_html( $this->publicize->get_service_label( $name ) ),
749
						esc_html( $this->publicize->get_display_name( $name, $connection ) )
750
					);
751
752
					if (
753
						$name === 'facebook'
754
					     && ! $this->publicize->is_valid_facebook_connection( $connection )
755
					     && $this->publicize->is_connecting_connection( $connection )
756
					) {
757
						$skip = true;
758
						$disabled = ' disabled="disabled"';
759
						$checked = false;
760
						$hidden_checkbox = false;
761
					}
762
763
					if ( ( !$skip || $done ) && ! $disabled ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $disabled of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
764
						$active[] = $label;
765
					}
766
767
					?>
768
					<li>
769
						<label for="wpas-submit-<?php echo esc_attr( $unique_id ); ?>">
770
							<input type="checkbox" name="wpas[submit][<?php echo $unique_id; ?>]" id="wpas-submit-<?php echo $unique_id; ?>" class="wpas-submit-<?php echo $name; ?>" value="1" <?php
771
								checked( true, $checked );
772
								echo $disabled;
773
							?> />
774
							<?php
775
							if ( $hidden_checkbox ) {
776
								// Need to submit a value to force a global connection to post
777
								echo '<input type="hidden" name="wpas[submit][' . $unique_id . ']" value="1" />';
778
							}
779
							echo esc_html( $label );
780
							?>
781
						</label>
782
					</li>
783
					<?php
784
				}
785
			}
786
787
			if ( $title = get_post_meta( $post->ID, $this->publicize->POST_MESS, true ) ) {
788
				$title = esc_html( $title );
789
			} else {
790
				$title = '';
791
			}
792
			?>
793
794
			</ul>
795
796
			<label for="wpas-title"><?php _e( 'Custom Message:', 'jetpack' ); ?></label>
797
			<span id="wpas-title-counter" class="alignright hide-if-no-js">0</span>
798
799
			<textarea name="wpas_title" id="wpas-title"<?php disabled( $all_done ); ?>><?php echo $title; ?></textarea>
800
801
			<a href="#" class="hide-if-no-js button" id="publicize-form-hide"><?php esc_html_e( 'OK', 'jetpack' ); ?></a>
802
			<input type="hidden" name="wpas[0]" value="1" />
803
804
		</div>
805
		<?php if ( ! $all_done ) : ?>
806
			<div id="pub-connection-tests"></div>
807
		<?php endif; ?>
808
		<?php // #publicize-form
809
810
		return array( ob_get_clean(), $active );
811
	}
812
813
814
	private function get_metabox_form_disconnected( $available_services ) {
815
		ob_start();
816
		?><div id="publicize-form" class="hide-if-js">
817
			<div id="add-publicize-check" style="display: none;"></div>
818
819
			<?php _e( 'Connect to', 'jetpack' ); ?>:
820
821
			<ul class="not-connected">
822
				<?php foreach ( $available_services as $service_name => $service ) : ?>
823
				<li>
824
					<a class="pub-service" data-service="<?php echo esc_attr( $service_name ); ?>" title="<?php echo esc_attr( sprintf( __( 'Connect and share your posts on %s', 'jetpack' ), $this->publicize->get_service_label( $service_name ) ) ); ?>" rel="noopener noreferrer" target="_blank" href="<?php echo esc_url( $this->publicize->connect_url( $service_name ) ); ?>">
825
						<?php echo esc_html( $this->publicize->get_service_label( $service_name ) ); ?>
826
					</a>
827
				</li>
828
				<?php endforeach; ?>
829
			</ul>
830
			<a href="#" class="hide-if-no-js button" id="publicize-disconnected-form-hide"><?php esc_html_e( 'OK', 'jetpack' ); ?></a>
831
		</div><?php // #publicize-form
832
		return ob_get_clean();
833
	}
834
}
835