Completed
Push — try/seperate-publicize-handlin... ( 77e1d0...27e7c1 )
by
unknown
06:45
created

Publicize_UI::connected_notice()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 2
nop 1
dl 0
loc 17
rs 9.7
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( 'options-general.php', __( 'Sharing Settings', 'jetpack' ), __( 'Sharing', 'jetpack' ), 'publish_posts', 'sharing', array( &$this, 'management_page' ) );
55
	}
56
57
58
	/**
59
	* Management page to load if Sharedaddy is not active so the 'pre_admin_screen_sharing' action exists.
60
	*/
61
	function management_page() { ?>
62
		<div class="wrap">
63
			<div class="icon32" id="icon-options-general"><br /></div>
64
			<h1><?php _e( 'Sharing Settings', 'jetpack' ); ?></h1>
65
66
				<?php
67
				/** This action is documented in modules/sharedaddy/sharing.php */
68
				do_action( 'pre_admin_screen_sharing' );
69
				?>
70
71
		</div> <?php
72
	}
73
74
	/**
75
	* styling for the sharing screen and popups
76
	* JS for the options and switching
77
	*/
78
	function load_assets() {
79
		wp_enqueue_script(
80
			'publicize',
81
			Jetpack::get_file_url_for_environment(
82
				'_inc/build/publicize/assets/publicize.min.js',
83
				'modules/publicize/assets/publicize.js'
84
			),
85
			array( 'jquery', 'thickbox' ),
86
			'20121019'
87
		);
88
		if ( is_rtl() ) {
89
			wp_enqueue_style( 'publicize', plugins_url( 'assets/rtl/publicize-rtl.css', __FILE__ ), array(), '20180301' );
90
		} else {
91
			wp_enqueue_style( 'publicize', plugins_url( 'assets/publicize.css', __FILE__ ), array(), '20180301' );
92
		}
93
94
		wp_enqueue_style( 'social-logos' );
95
96
		add_thickbox();
97
	}
98
99
	public static function connected_notice( $service_name ) { ?>
100
		<div class='updated'>
101
			<p><?php
102
103
			if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
104
				$platform =  __( 'WordPress.com', 'jetpack' );
105
			} else {
106
				$platform = __( 'Jetpack', 'jetpack' );
107
			}
108
109
			printf(
110
				__( 'You have successfully connected your %1$s account with %2$s.', '1: Service Name (Facebook, Twitter, ...), 2. WordPress.com or Jetpack', 'jetpack' ),
111
				Publicize::get_service_label( $service_name ),
112
				$platform
113
			); ?></p>
114
		</div><?php
115
	}
116
117
	public static function denied_notice() { ?>
118
		<div class='updated'>
119
			<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>
120
		</div><?php
121
	}
122
123
	/**
124
	* Lists the current user's publicized accounts for the blog
125
	* looks exactly like Publicize v1 for now, UI and functionality updates will come after the move to keyring
126
	*/
127
	function admin_page() {
128
		$_blog_id = get_current_blog_id();
129
		?>
130
131
		<form action="" id="publicize-form">
132
			<h2 id="publicize"><?php _e( 'Publicize', 'jetpack' ) ?></h2>
133
134
			<?php
135
				if ( ! empty( $_GET['action'] ) && 'deny' == $_GET['action'] ) {
136
					$this->denied_notice();
137
				}
138
			?>
139
140
			<?php
141
				if ( ! empty ( $_GET['action'] ) && 'error' == $_GET['action'] ) {
142
					$this->display_connection_error();
0 ignored issues
show
Bug introduced by
The method display_connection_error() does not seem to exist on object<Publicize_UI>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
143
				}
144
			?>
145
146
			<p>
147
				<?php esc_html_e( 'Connect your blog to popular social networking sites and automatically share new posts with your friends.', 'jetpack' ) ?>
148
				<?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' ); ?>
149
			</p>
150
151
			<?php
152
			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...
153
				$doc_link = "http://jetpack.com/support/publicize/";
154
			} else {
155
				$doc_link = "http://en.support.wordpress.com/publicize/";
156
			}
157
			?>
158
159
			<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>
160
161
			<div id="publicize-services-block">
162
				<?php
163
				$services = $this->publicize->get_services( 'all' );
164
				$total_num_of_services = count ( $services );
165
				$service_num = 0;?>
166
167
				<div class='left'>
168
169
				<?php
170
				foreach ( $services as $name => $service ) :
171
					$connect_url = $this->publicize->connect_url( $name );
172
					if ( $service_num == ( round ( ( $total_num_of_services / 2 ), 0 ) ) )
173
						echo "</div><div class='right'>";
174
					$service_num++;
175
					?>
176
					<div class="publicize-service-entry" <?php if ( $service_num > 0 ): ?>class="connected"<?php endif; ?> >
177
						<div id="<?php echo esc_attr( $name ); ?>" class="publicize-service-left">
178
							<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>
179
						</div>
180
181
182
						<div class="publicize-service-right">
183
							<?php if ( $this->publicize->is_enabled( $name ) && $connections = $this->publicize->get_connections( $name ) ) : ?>
184
								<ul>
185
									<?php
186
									foreach( $connections as $c ) :
187
										$id = $this->publicize->get_connection_id( $c );
188
										$disconnect_url = $this->publicize->disconnect_url( $name, $id );
189
190
										$cmeta = $this->publicize->get_connection_meta( $c );
191
										$profile_link = $this->publicize->get_profile_link( $name, $c );
192
										$connection_display = $this->publicize->get_display_name( $name, $c );
193
194
										$options_nonce = wp_create_nonce( 'options_page_' . $name . '_' . $id ); ?>
195
196
										<?php if ( $this->publicize->show_options_popup( $name, $c ) ): ?>
197
										<script type="text/javascript">
198
										jQuery(document).ready( function($) {
199
											showOptionsPage.call(
200
											this,
201
											'<?php echo esc_js( $name ); ?>',
202
											'<?php echo esc_js( $options_nonce ); ?>',
203
											'<?php echo esc_js( $id ); ?>'
204
											);
205
										} );
206
										</script>
207
										<?php endif; ?>
208
209
										<li class="publicize-connection" data-connection-id="<?php echo esc_attr( $id ); ?>">
210
											<?php esc_html_e( 'Connected as:', 'jetpack' ); ?>
211
											<?php
212
											if ( !empty( $profile_link ) ) : ?>
213
												<a class="publicize-profile-link" href="<?php echo esc_url( $profile_link ); ?>" target="_top">
214
													<?php echo esc_html( $connection_display ); ?>
215
												</a><?php
216
											else :
217
												echo esc_html( $connection_display );
218
											endif;
219
											?>
220
221
											<?php if ( 0 == $cmeta['connection_data']['user_id'] ) : ?>
222
												<small>(<?php esc_html_e( 'Shared', 'jetpack' ); ?>)</small>
223
224
												<?php if ( current_user_can( $this->publicize->GLOBAL_CAP ) ) : ?>
225
													<a class="pub-disconnect-button" title="<?php esc_html_e( 'Disconnect', 'jetpack' ); ?>" href="<?php echo esc_url( $disconnect_url ); ?>" target="_top">×</a>
226
												<?php endif; ?>
227
228
											<?php else : ?>
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
											<br/>
233
											<div class="pub-connection-test test-in-progress" id="pub-connection-test-<?php echo esc_attr( $id ); ?>" >
234
											</div>
235
										</li>
236
237
										<?php
238
									endforeach;
239
									?>
240
								</ul>
241
							<?php endif; ?>
242
243
244
245
							<?php
246
								$connections = $this->publicize->get_connections( $name );
247
								if ( empty ( $connections ) ) { ?>
248
									<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>
249
								<?php } else { ?>
250
									<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>
251
			  					<?php } ?>
252
			  			</div>
253
			  		</div>
254
				<?php endforeach; ?>
255
				</div>
256
				<script>
257
				(function($){
258
					$('.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' ) ); ?>' ) ) {
259
								return true;
260
							} else {
261
							e.preventDefault();
262
							return false;
263
						}
264
					})
265
				})(jQuery);
266
				</script>
267
			</div>
268
269
			<?php wp_nonce_field( "wpas_posts_{$_blog_id}", "_wpas_posts_{$_blog_id}_nonce" ); ?>
270
			<input type="hidden" id="wpas_ajax_blog_id" name="wpas_ajax_blog_id" value="<?php echo $_blog_id; ?>" />
271
		</form><?php
272
273
	}
274
275
	public static function global_checkbox( $service_name, $id ) {
276
		global $publicize;
277
		if ( current_user_can( $publicize->GLOBAL_CAP ) ) : ?>
278
			<p>
279
				<input id="globalize_<?php echo $service_name; ?>" type="checkbox" name="global" value="<?php echo wp_create_nonce( 'publicize-globalize-' . $id ) ?>" />
280
				<label for="globalize_<?php echo $service_name; ?>"><?php _e( 'Make this connection available to all users of this blog?', 'jetpack' ); ?></label>
281
			</p>
282
		<?php endif;
283
	}
284
285
	function broken_connection( $service_name, $id ) { ?>
286
		<div id="thickbox-content">
287
			<div class='error'>
288
				<p><?php printf( __( 'There was a problem connecting to %s. Please disconnect and try again.', 'jetpack' ), Publicize::get_service_label( $service_name ) ); ?></p>
289
			</div>
290
		</div><?php
291
	}
292
293
	public static function options_page_other( $service_name ) {
294
		// Nonce check
295
		check_admin_referer( "options_page_{$service_name}_" . $_REQUEST['connection'] );
296
		?>
297
		<div id="thickbox-content">
298
			<?php
299
			ob_start();
300
			Publicize_UI::connected_notice( $service_name );
301
			$update_notice = ob_get_clean();
302
			if ( ! empty( $update_notice ) )
303
				echo $update_notice;
304
			?>
305
306
			<?php Publicize_UI::global_checkbox( $service_name, $_REQUEST['connection'] ); ?>
307
308
			<p style="text-align: center;">
309
				<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'] ) ?>" />
310
			</p> <br />
311
		</div>
312
		<?php
313
	}
314
315
	/**
316
	* CSS for styling the publicize message box and counter that displays on the post page.
317
	* There is also some JavaScript for length counting and some basic display effects.
318
	*/
319
	function post_page_metabox_assets() {
320
		global $post;
321
		$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...
322
323
		$default_prefix = $this->publicize->default_prefix;
324
		$default_prefix = preg_replace( '/%([0-9])\$s/', "' + %\\1\$s + '", esc_js( $default_prefix ) );
325
326
		$default_message = $this->publicize->default_message;
327
		$default_message = preg_replace( '/%([0-9])\$s/', "' + %\\1\$s + '", esc_js( $default_message ) );
328
329
		$default_suffix = $this->publicize->default_suffix;
330
		$default_suffix = preg_replace( '/%([0-9])\$s/', "' + %\\1\$s + '", esc_js( $default_suffix ) ); ?>
331
332
<script type="text/javascript">
333
jQuery( function($) {
334
	var wpasTitleCounter    = $( '#wpas-title-counter' ),
335
		wpasTwitterCheckbox = $( '.wpas-submit-twitter' ).length,
336
		wpasTitle = $('#wpas-title').keyup( function() {
337
		var length = wpasTitle.val().length;
338
		wpasTitleCounter.text( length );
339
		if ( wpasTwitterCheckbox && length > 256 ) {
340
			wpasTitleCounter.addClass( 'wpas-twitter-length-limit' );
341
		} else {
342
			wpasTitleCounter.removeClass( 'wpas-twitter-length-limit' );
343
		}
344
		} ),
345
		authClick = false;
346
347
	$('#publicize-disconnected-form-show').click( function() {
348
		$('#publicize-form').slideDown( 'fast' );
349
		$(this).hide();
350
	} );
351
352
	$('#publicize-disconnected-form-hide').click( function() {
353
		$('#publicize-form').slideUp( 'fast' );
354
		$('#publicize-disconnected-form-show').show();
355
	} );
356
357
	$('#publicize-form-edit').click( function() {
358
		$('#publicize-form').slideDown( 'fast', function() {
359
			wpasTitle.focus();
360
			if ( !wpasTitle.text() ) {
361
				var url = $('#shortlink').length ? $('#shortlink').val() : '';
362
363
				var defaultMessage = $.trim( '<?php printf( $default_prefix, 'url' ); printf( $default_message, '$("#title").val()', 'url' ); printf( $default_suffix, 'url' ); ?>' );
364
365
				wpasTitle.append( defaultMessage.replace( /<[^>]+>/g,'') );
366
367
				var selBeg = defaultMessage.indexOf( $("#title").val() );
368
				if ( selBeg < 0 ) {
369
					selBeg = 0;
370
					selEnd = 0;
371
				} else {
372
					selEnd = selBeg + $("#title").val().length;
373
				}
374
375
				var domObj = wpasTitle.get(0);
376
				if ( domObj.setSelectionRange ) {
377
					domObj.setSelectionRange( selBeg, selEnd );
378
				} else if ( domObj.createTextRange ) {
379
					var r = domObj.createTextRange();
380
					r.moveStart( 'character', selBeg );
381
					r.moveEnd( 'character', selEnd );
382
					r.select();
383
				}
384
			}
385
			wpasTitle.keyup();
386
		} );
387
		$('#publicize-defaults').hide();
388
		$(this).hide();
389
		return false;
390
	} );
391
392
	$('#publicize-form-hide').click( function() {
393
		var newList = $.map( $('#publicize-form').slideUp( 'fast' ).find( ':checked' ), function( el ) {
394
			return $.trim( $(el).parent( 'label' ).text() );
395
		} );
396
		$('#publicize-defaults').html( '<strong>' + newList.join( '</strong>, <strong>' ) + '</strong>' ).show();
397
		$('#publicize-form-edit').show();
398
		return false;
399
	} );
400
401
	$('.authorize-link').click( function() {
402
		if ( authClick ) {
403
			return false;
404
		}
405
		authClick = true;
406
		$(this).after( '<img src="images/loading.gif" class="alignleft" style="margin: 0 .5em" />' );
407
		$.ajaxSetup( { async: false } );
408
409
		if ( window.wp && window.wp.autosave ) {
410
			window.wp.autosave.server.triggerSave();
411
		} else {
412
			autosave();
413
		}
414
415
		return true;
416
	} );
417
418
	$( '.pub-service' ).click( function() {
419
		var service = $(this).data( 'service' ),
420
			fakebox = '<input id="wpas-submit-' + service + '" type="hidden" value="1" name="wpas[submit][' + service + ']" />';
421
		$( '#add-publicize-check' ).append( fakebox );
422
	} );
423
424
	publicizeConnTestStart = function() {
425
		$( '#pub-connection-tests' )
426
			.removeClass( 'below-h2' )
427
			.removeClass( 'error' )
428
			.removeClass( 'publicize-token-refresh-message' )
429
			.addClass( 'test-in-progress' )
430
			.html( '' );
431
		$.post( ajaxurl, { action: 'test_publicize_conns' }, publicizeConnTestComplete );
432
	}
433
434
	publicizeConnRefreshClick = function( event ) {
435
		event.preventDefault();
436
		var popupURL = event.currentTarget.href;
437
		var popupTitle = event.currentTarget.title;
438
		// open a popup window
439
		// when it is closed, kick off the tests again
440
		var popupWin = window.open( popupURL, popupTitle, '' );
441
		var popupWinTimer= window.setInterval( function() {
442
			if ( popupWin.closed !== false ) {
443
				window.clearInterval( popupWinTimer );
444
				publicizeConnTestStart();
445
			}
446
		}, 500 );
447
	}
448
449
	publicizeConnTestComplete = function( response ) {
450
		var testsSelector = $( '#pub-connection-tests' );
451
		testsSelector
452
			.removeClass( 'test-in-progress' )
453
			.removeClass( 'below-h2' )
454
			.removeClass( 'error' )
455
			.removeClass( 'publicize-token-refresh-message' )
456
			.html( '' );
457
458
		// If any of the tests failed, show some stuff
459
		var somethingShownAlready = false;
460
		var facebookNotice = false;
461
		$.each( response.data, function( index, testResult ) {
462
463
			// find the li for this connection
464
			if ( ! testResult.connectionTestPassed && testResult.userCanRefresh ) {
465
				if ( ! somethingShownAlready ) {
466
					testsSelector
467
						.addClass( 'below-h2' )
468
						.addClass( 'error' )
469
						.addClass( 'publicize-token-refresh-message' )
470
						.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>" );
471
					somethingShownAlready = true;
472
				}
473
474
				if ( testResult.userCanRefresh ) {
475
					testsSelector.append( '<p/>' );
476
					$( '<a/>', {
477
						'class'  : 'pub-refresh-button button',
478
						'title'  : testResult.refreshText,
479
						'href'   : testResult.refreshURL,
480
						'text'   : testResult.refreshText,
481
						'target' : '_refresh_' + testResult.serviceName
482
					} )
483
						.appendTo( testsSelector.children().last() )
484
						.click( publicizeConnRefreshClick );
485
				}
486
			}
487
488
			if( ! testResult.connectionTestPassed && ! testResult.userCanRefresh ) {
489
490
				$( '#wpas-submit-' + testResult.unique_id ).prop( "checked", false ).prop( "disabled", true );
491
				if ( ! facebookNotice ) {
492
					var message = '<p>'
493
						+ testResult.connectionTestMessage
494
						+ '</p><p>'
495
						+ ' <a class="button" href="<?php echo esc_url( admin_url( 'options-general.php?page=sharing' ) ); ?>" rel="noopener noreferrer" target="_blank">'
496
						+ '<?php echo esc_html( __( 'Update Your Sharing Settings' ,'jetpack' ) ); ?>'
497
						+ '</a>'
498
						+ '<p>';
499
500
					testsSelector
501
						.addClass( 'below-h2' )
502
						.addClass( 'error' )
503
						.addClass( 'publicize-token-refresh-message' )
504
						.append( message );
505
					facebookNotice = true;
506
				}
507
508
			}
509
510
511
		} );
512
	}
513
514
	$( document ).ready( function() {
515
		// If we have the #pub-connection-tests div present, kick off the connection test
516
		if ( $( '#pub-connection-tests' ).length ) {
517
			publicizeConnTestStart();
518
		}
519
	} );
520
521
} );
522
</script>
523
524
<style type="text/css">
525
#publicize {
526
	line-height: 1.5;
527
}
528
#publicize ul {
529
	margin: 4px 0 4px 6px;
530
}
531
#publicize li {
532
	margin: 0;
533
}
534
#publicize textarea {
535
	margin: 4px 0 0;
536
	width: 100%
537
}
538
#publicize ul.not-connected {
539
	list-style: square;
540
	padding-left: 1em;
541
}
542
#publicize-title:before {
543
	content: "\f237";
544
	font: normal 20px/1 dashicons;
545
	speak: none;
546
	margin-left: -1px;
547
	padding-right: 3px;
548
	vertical-align: top;
549
	-webkit-font-smoothing: antialiased;
550
	color: #82878c;
551
}
552
.post-new-php .authorize-link, .post-php .authorize-link {
553
	line-height: 1.5em;
554
}
555
.post-new-php .authorize-message, .post-php .authorize-message {
556
	margin-bottom: 0;
557
}
558
#poststuff #publicize .updated p {
559
	margin: .5em 0;
560
}
561
.wpas-twitter-length-limit {
562
	color: red;
563
}
564
</style><?php
565
	}
566
567
	/**
568
	* Controls the metabox that is displayed on the post page
569
	* Allows the user to customize the message that will be sent out to the social network, as well as pick which
570
	* networks to publish to. Also displays the character counter and some other information.
571
	*/
572
	function post_page_metabox() {
573
		global $post;
574
575
		if ( ! $this->publicize->post_type_is_publicizeable( $post->post_type ) )
576
			return;
577
578
		$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...
579
		$services = $this->publicize->get_services( 'connected' );
580
		$available_services = $this->publicize->get_services( 'all' );
581
582
		if ( ! is_array( $available_services ) )
583
			$available_services = array();
584
585
		if ( ! is_array( $services ) )
586
			$services = array();
587
		?>
588
		<div id="publicize" class="misc-pub-section misc-pub-section-last">
589
			<span id="publicize-title">
590
				<?php esc_html_e( 'Publicize:', 'jetpack' ); ?>
591
				<?php if ( 0 < count( $services ) ) : ?>
592
					<?php list( $publicize_form, $active ) = $this->get_metabox_form_connected( $services ); ?>
593
					<span id="publicize-defaults">
594
						<?php foreach ( $active as $item ) : ?>
595
							<strong><?php echo esc_html( $item ); ?></strong>
596
						<?php endforeach; ?>
597
					</span>
598
					<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 />
599
				<?php else : ?>
600
					<?php $publicize_form = $this->get_metabox_form_disconnected( $available_services ); ?>
601
					<strong><?php echo __( 'Not Connected', 'jetpack' ); ?></strong>
602
					<a href="#" id="publicize-disconnected-form-show"><?php esc_html_e( 'Edit', 'jetpack' ); ?></a><br />
603
				<?php endif; ?>
604
			</span>
605
			<?php
606
			/**
607
			 * Filter the Publicize details form.
608
			 *
609
			 * @module publicize
610
			 *
611
			 * @since 2.0.0
612
			 *
613
			 * @param string $publicize_form Publicize Details form appearing above Publish button in the editor.
614
			 */
615
			echo apply_filters( 'publicize_form', $publicize_form );
616
			?>
617
		</div> <?php // #publicize
618
	}
619
620
	private function get_metabox_form_connected( $services ) {
621
		global $post;
622
		$active = array();
623
		ob_start();
624
		?> <div id="publicize-form" class="hide-if-js">
625
			<ul>
626
627
			<?php
628
			// We can set an _all flag to indicate that this post is completely done as
629
			// far as Publicize is concerned. Jetpack uses this approach. All published posts in Jetpack
630
			// have Publicize disabled.
631
			$all_done = get_post_meta( $post->ID, $this->publicize->POST_DONE . 'all', true ) || ( $this->in_jetpack && 'publish' == $post->post_status );
632
633
			// We don't allow Publicizing to the same external id twice, to prevent spam
634
			$service_id_done = (array) get_post_meta( $post->ID, $this->publicize->POST_SERVICE_DONE, true );
635
636
			foreach ( $services as $name => $connections ) {
637
				foreach ( $connections as $connection ) {
638
					$connection_data = '';
639 View Code Duplication
					if ( method_exists( $connection, 'get_meta' ) )
640
						$connection_data = $connection->get_meta( 'connection_data' );
641
					elseif ( ! empty( $connection['connection_data'] ) )
642
						$connection_data = $connection['connection_data'];
643
644
					/**
645
					 * Filter whether a post should be publicized to a given service.
646
					 *
647
					 * @module publicize
648
					 *
649
					 * @since 2.0.0
650
					 *
651
					 * @param bool true Should the post be publicized to a given service? Default to true.
652
					 * @param int $post->ID Post ID.
653
					 * @param string $name Service name.
654
					 * @param array $connection_data Array of information about all Publicize details for the site.
655
					 */
656
					if ( ! $continue = apply_filters( 'wpas_submit_post?', true, $post->ID, $name, $connection_data ) ) {
657
						continue;
658
					}
659
660 View Code Duplication
					if ( ! empty( $connection->unique_id ) ) {
661
						$unique_id = $connection->unique_id;
662
					} else if ( ! empty( $connection['connection_data']['token_id'] ) ) {
663
						$unique_id = $connection['connection_data']['token_id'];
664
					}
665
666
					// Should we be skipping this one?
667
					$skip = (
668
						(
669
							in_array( $post->post_status, array( 'publish', 'draft', 'future' ) )
670
							&&
671
							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...
672
						)
673
						||
674
						(
675
							is_array( $connection )
676
							&&
677
							(
678
								( isset( $connection['meta']['external_id'] ) && ! empty( $service_id_done[ $name ][ $connection['meta']['external_id'] ] ) )
679
								||
680
								// Jetpack's connection data looks a little different.
681
								( isset( $connection['external_id'] ) && ! empty( $service_id_done[ $name ][ $connection['external_id'] ] ) )
682
							)
683
						)
684
					);
685
686
					// Was this connections (OR, old-format service) already Publicized to?
687
					$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
688
689
					// If this one has already been publicized to, don't let it happen again
690
					$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...
691
					if ( $done ) {
692
						$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...
693
					}
694
695
					// If this is a global connection and this user doesn't have enough permissions to modify
696
					// those connections, don't let them change it
697
					$cmeta = $this->publicize->get_connection_meta( $connection );
698
					$hidden_checkbox = false;
699
					if ( !$done && ( 0 == $cmeta['connection_data']['user_id'] && !current_user_can( $this->publicize->GLOBAL_CAP ) ) ) {
700
						$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...
701
						/**
702
						 * Filters the checkboxes for global connections with non-prilvedged users.
703
						 *
704
						 * @module publicize
705
						 *
706
						 * @since 3.7.0
707
						 *
708
						 * @param bool   $checked Indicates if this connection should be enabled. Default true.
709
						 * @param int    $post->ID ID of the current post
710
						 * @param string $name Name of the connection (Facebook, Twitter, etc)
711
						 * @param array  $connection Array of data about the connection.
712
						 */
713
						$hidden_checkbox = apply_filters( 'publicize_checkbox_global_default', true, $post->ID, $name, $connection );
714
					}
715
716
					// Determine the state of the checkbox (on/off) and allow filtering
717
					$checked = $skip != 1 || $done;
718
					/**
719
					 * Filter the checkbox state of each Publicize connection appearing in the post editor.
720
					 *
721
					 * @module publicize
722
					 *
723
					 * @since 2.0.1
724
					 *
725
					 * @param bool $checked Should the Publicize checkbox be enabled for a given service.
726
					 * @param int $post->ID Post ID.
727
					 * @param string $name Service name.
728
					 * @param array $connection Array of connection details.
729
					 */
730
					$checked = apply_filters( 'publicize_checkbox_default', $checked, $post->ID, $name, $connection );
731
732
					// Force the checkbox to be checked if the post was DONE, regardless of what the filter does
733
					if ( $done ) {
734
						$checked = true;
735
					}
736
					$disabled = false;
737
					// This post has been handled, so disable everything
738
					if ( $all_done ) {
739
						$disabled = ' disabled="disabled"';
740
					}
741
742
					$label = sprintf(
743
						_x( '%1$s: %2$s', 'Service: Account connected as', 'jetpack' ),
744
						esc_html( $this->publicize->get_service_label( $name ) ),
745
						esc_html( $this->publicize->get_display_name( $name, $connection ) )
746
					);
747
748
					if (
749
						$name === 'facebook'
750
					     && ! $this->publicize->is_valid_facebook_connection( $connection )
751
					     && $this->publicize->is_connecting_connection( $connection )
752
					) {
753
						$skip = true;
754
						$disabled = ' disabled="disabled"';
755
						$checked = false;
756
						$hidden_checkbox = false;
757
					}
758
759
					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...
760
						$active[] = $label;
761
					}
762
763
					?>
764
					<li>
765
						<label for="wpas-submit-<?php echo esc_attr( $unique_id ); ?>">
766
							<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
767
								checked( true, $checked );
768
								echo $disabled;
769
							?> />
770
							<?php
771
							if ( $hidden_checkbox ) {
772
								// Need to submit a value to force a global connection to post
773
								echo '<input type="hidden" name="wpas[submit][' . $unique_id . ']" value="1" />';
774
							}
775
							echo esc_html( $label );
776
							?>
777
						</label>
778
					</li>
779
					<?php
780
				}
781
			}
782
783
			if ( $title = get_post_meta( $post->ID, $this->publicize->POST_MESS, true ) ) {
784
				$title = esc_html( $title );
785
			} else {
786
				$title = '';
787
			}
788
			?>
789
790
			</ul>
791
792
			<label for="wpas-title"><?php _e( 'Custom Message:', 'jetpack' ); ?></label>
793
			<span id="wpas-title-counter" class="alignright hide-if-no-js">0</span>
794
795
			<textarea name="wpas_title" id="wpas-title"<?php disabled( $all_done ); ?>><?php echo $title; ?></textarea>
796
797
			<a href="#" class="hide-if-no-js button" id="publicize-form-hide"><?php esc_html_e( 'OK', 'jetpack' ); ?></a>
798
			<input type="hidden" name="wpas[0]" value="1" />
799
800
		</div>
801
		<?php if ( ! $all_done ) : ?>
802
			<div id="pub-connection-tests"></div>
803
		<?php endif; ?>
804
		<?php // #publicize-form
805
806
		return array( ob_get_clean(), $active );
807
	}
808
809
810
	private function get_metabox_form_disconnected( $available_services ) {
811
		ob_start();
812
		?><div id="publicize-form" class="hide-if-js">
813
			<div id="add-publicize-check" style="display: none;"></div>
814
815
			<?php _e( 'Connect to', 'jetpack' ); ?>:
816
817
			<ul class="not-connected">
818
				<?php foreach ( $available_services as $service_name => $service ) : ?>
819
				<li>
820
					<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 ) ); ?>">
821
						<?php echo esc_html( $this->publicize->get_service_label( $service_name ) ); ?>
822
					</a>
823
				</li>
824
				<?php endforeach; ?>
825
			</ul>
826
			<a href="#" class="hide-if-no-js button" id="publicize-disconnected-form-hide"><?php esc_html_e( 'OK', 'jetpack' ); ?></a>
827
		</div><?php // #publicize-form
828
		return ob_get_clean();
829
	}
830
}
831