Completed
Push — try/seperate-publicize-handlin... ( a92583...f77f43 )
by
unknown
09:09
created

Publicize_UI::disconnected_notice()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 5
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
		add_action( 'connection_disconnected', array( __CLASS__, 'add_disconnect_notice' ) );
49
	}
50
51
	/**
52
	* If the ShareDaddy plugin is not active we need to add the sharing settings page to the menu still
53
	*/
54
	function sharing_menu() {
55
		add_submenu_page( 'options-general.php', __( 'Sharing Settings', 'jetpack' ), __( 'Sharing', 'jetpack' ), 'publish_posts', 'sharing', array( &$this, 'management_page' ) );
56
	}
57
58
59
	/**
60
	* Management page to load if Sharedaddy is not active so the 'pre_admin_screen_sharing' action exists.
61
	*/
62
	function management_page() { ?>
63
		<div class="wrap">
64
			<div class="icon32" id="icon-options-general"><br /></div>
65
			<h1><?php _e( 'Sharing Settings', 'jetpack' ); ?></h1>
66
67
				<?php
68
				/** This action is documented in modules/sharedaddy/sharing.php */
69
				do_action( 'pre_admin_screen_sharing' );
70
				?>
71
72
		</div> <?php
73
	}
74
75
	/**
76
	* styling for the sharing screen and popups
77
	* JS for the options and switching
78
	*/
79
	function load_assets() {
80
		wp_enqueue_script(
81
			'publicize',
82
			Jetpack::get_file_url_for_environment(
83
				'_inc/build/publicize/assets/publicize.min.js',
84
				'modules/publicize/assets/publicize.js'
85
			),
86
			array( 'jquery', 'thickbox' ),
87
			'20121019'
88
		);
89
		if ( is_rtl() ) {
90
			wp_enqueue_style( 'publicize', plugins_url( 'assets/rtl/publicize-rtl.css', __FILE__ ), array(), '20180301' );
91
		} else {
92
			wp_enqueue_style( 'publicize', plugins_url( 'assets/publicize.css', __FILE__ ), array(), '20180301' );
93
		}
94
95
		wp_enqueue_style( 'social-logos' );
96
97
		add_thickbox();
98
	}
99
100
	public static function connected_notice( $service_name ) { ?>
101
		<div class='updated'>
102
			<p><?php
103
104
			if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
105
				$platform =  __( 'WordPress.com', 'jetpack' );
106
			} else {
107
				$platform = __( 'Jetpack', 'jetpack' );
108
			}
109
110
			printf(
111
				__( 'You have successfully connected your %1$s account with %2$s.', '1: Service Name (Facebook, Twitter, ...), 2. WordPress.com or Jetpack', 'jetpack' ),
112
				Publicize::get_service_label( $service_name ),
113
				$platform
114
			); ?></p>
115
		</div><?php
116
	}
117
118
	public static function add_disconnect_notice() {
119
		add_action( 'admin_notices', array( __CLASS__, 'disconnected_notice' ) );
120
	}
121
122
	public static function disconnected_notice() {
123
		echo "<div class='updated'>\n";
124
		echo '<p>' . esc_html(__( 'That connection has been removed.', 'jetpack' ) ) . "</p>\n";
125
		echo "</div>\n\n";
126
	}
127
128
	public static function denied_notice() { ?>
129
		<div class='updated'>
130
			<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>
131
		</div><?php
132
	}
133
134
	function admin_page_warning() {
135
		$jetpack   = Jetpack::init();
136
		$blog_name = get_bloginfo( 'blogname' );
137
		if ( empty( $blog_name ) ) {
138
			$blog_name = home_url( '/' );
139
		}
140
141
		?>
142
		<div id="message" class="updated jetpack-message jp-connect">
143
			<div class="jetpack-wrap-container">
144
				<div class="jetpack-text-container">
145
					<p><?php printf(
146
							/* translators: %s is the name of the blog */
147
							esc_html( wptexturize( __( "To use Publicize, you'll need to link your %s account to your WordPress.com account using the link below.", 'jetpack' ) ) ),
148
							'<strong>' . esc_html( $blog_name ) . '</strong>'
149
						); ?></p>
150
					<p><?php echo esc_html( wptexturize( __( "If you don't have a WordPress.com account yet, you can sign up for free in just a few seconds.", 'jetpack' ) ) ); ?></p>
151
				</div>
152
				<div class="jetpack-install-container">
153
					<p class="submit"><a
154
							href="<?php echo $jetpack->build_connect_url( false, menu_page_url( 'sharing', false ) ); ?>"
155
							class="button-connector"
156
							id="wpcom-connect"><?php esc_html_e( 'Link account with WordPress.com', 'jetpack' ); ?></a>
157
					</p>
158
					<p class="jetpack-install-blurb">
159
						<?php jetpack_render_tos_blurb(); ?>
160
					</p>
161
				</div>
162
			</div>
163
		</div>
164
		<?php
165
	}
166
167
	/**
168
	* Lists the current user's publicized accounts for the blog
169
	* looks exactly like Publicize v1 for now, UI and functionality updates will come after the move to keyring
170
	*/
171
	function admin_page() {
172
		$_blog_id = get_current_blog_id();
173
		?>
174
175
		<form action="" id="publicize-form">
176
			<h2 id="publicize"><?php _e( 'Publicize', 'jetpack' ) ?></h2>
177
178
			<?php
179
				if ( ! empty( $_GET['action'] ) && 'deny' == $_GET['action'] ) {
180
					$this->denied_notice();
181
				}
182
			?>
183
184
			<p>
185
				<?php esc_html_e( 'Connect your blog to popular social networking sites and automatically share new posts with your friends.', 'jetpack' ) ?>
186
				<?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' ); ?>
187
			</p>
188
189
			<?php
190
			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...
191
				$doc_link = "http://jetpack.com/support/publicize/";
192
			} else {
193
				$doc_link = "http://en.support.wordpress.com/publicize/";
194
			}
195
			?>
196
197
			<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>
198
199
			<div id="publicize-services-block">
200
				<?php
201
				$services = $this->publicize->get_services( 'all' );
202
				$total_num_of_services = count ( $services );
203
				$service_num = 0;?>
204
205
				<div class='left'>
206
207
				<?php
208
				foreach ( $services as $name => $service ) :
209
					$connect_url = $this->publicize->connect_url( $name );
210
					if ( $service_num == ( round ( ( $total_num_of_services / 2 ), 0 ) ) )
211
						echo "</div><div class='right'>";
212
					$service_num++;
213
					?>
214
					<div class="publicize-service-entry" <?php if ( $service_num > 0 ): ?>class="connected"<?php endif; ?> >
215
						<div id="<?php echo esc_attr( $name ); ?>" class="publicize-service-left">
216
							<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>
217
						</div>
218
219
220
						<div class="publicize-service-right">
221
							<?php if ( $this->publicize->is_enabled( $name ) && $connections = $this->publicize->get_connections( $name ) ) : ?>
222
								<ul>
223
									<?php
224
									foreach( $connections as $c ) :
225
										$id = $this->publicize->get_connection_id( $c );
226
										$disconnect_url = $this->publicize->disconnect_url( $name, $id );
227
228
										$cmeta = $this->publicize->get_connection_meta( $c );
229
										$profile_link = $this->publicize->get_profile_link( $name, $c );
230
										$connection_display = $this->publicize->get_display_name( $name, $c );
231
232
										$options_nonce = wp_create_nonce( 'options_page_' . $name . '_' . $id ); ?>
233
234
										<?php if ( $this->publicize->show_options_popup( $name, $c ) ): ?>
235
										<script type="text/javascript">
236
										jQuery(document).ready( function($) {
237
											showOptionsPage.call(
238
											this,
239
											'<?php echo esc_js( $name ); ?>',
240
											'<?php echo esc_js( $options_nonce ); ?>',
241
											'<?php echo esc_js( $id ); ?>'
242
											);
243
										} );
244
										</script>
245
										<?php endif; ?>
246
247
										<li class="publicize-connection" data-connection-id="<?php echo esc_attr( $id ); ?>">
248
											<?php esc_html_e( 'Connected as:', 'jetpack' ); ?>
249
											<?php
250
											if ( !empty( $profile_link ) ) : ?>
251
												<a class="publicize-profile-link" href="<?php echo esc_url( $profile_link ); ?>" target="_top">
252
													<?php echo esc_html( $connection_display ); ?>
253
												</a><?php
254
											else :
255
												echo esc_html( $connection_display );
256
											endif;
257
											?>
258
259
											<?php if ( 0 == $cmeta['connection_data']['user_id'] ) : ?>
260
												<small>(<?php esc_html_e( 'Shared', 'jetpack' ); ?>)</small>
261
262
												<?php if ( current_user_can( $this->publicize->GLOBAL_CAP ) ) : ?>
263
													<a class="pub-disconnect-button" title="<?php esc_html_e( 'Disconnect', 'jetpack' ); ?>" href="<?php echo esc_url( $disconnect_url ); ?>" target="_top">×</a>
264
												<?php endif; ?>
265
266
											<?php else : ?>
267
												<a class="pub-disconnect-button" title="<?php esc_html_e( 'Disconnect', 'jetpack' ); ?>" href="<?php echo esc_url( $disconnect_url ); ?>" target="_top">×</a>
268
											<?php endif; ?>
269
270
											<br/>
271
											<div class="pub-connection-test test-in-progress" id="pub-connection-test-<?php echo esc_attr( $id ); ?>" >
272
											</div>
273
										</li>
274
275
										<?php
276
									endforeach;
277
									?>
278
								</ul>
279
							<?php endif; ?>
280
281
282
283
							<?php
284
								$connections = $this->publicize->get_connections( $name );
285
								if ( empty ( $connections ) ) { ?>
286
									<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>
287
								<?php } else { ?>
288
									<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>
289
			  					<?php } ?>
290
			  			</div>
291
			  		</div>
292
				<?php endforeach; ?>
293
				</div>
294
				<script>
295
				(function($){
296
					$('.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' ) ); ?>' ) ) {
297
								return true;
298
							} else {
299
							e.preventDefault();
300
							return false;
301
						}
302
					})
303
				})(jQuery);
304
				</script>
305
			</div>
306
307
			<?php wp_nonce_field( "wpas_posts_{$_blog_id}", "_wpas_posts_{$_blog_id}_nonce" ); ?>
308
			<input type="hidden" id="wpas_ajax_blog_id" name="wpas_ajax_blog_id" value="<?php echo $_blog_id; ?>" />
309
		</form><?php
310
311
	}
312
313
	public static function global_checkbox( $service_name, $id ) {
314
		global $publicize;
315
		if ( current_user_can( $publicize->GLOBAL_CAP ) ) : ?>
316
			<p>
317
				<input id="globalize_<?php echo $service_name; ?>" type="checkbox" name="global" value="<?php echo wp_create_nonce( 'publicize-globalize-' . $id ) ?>" />
318
				<label for="globalize_<?php echo $service_name; ?>"><?php _e( 'Make this connection available to all users of this blog?', 'jetpack' ); ?></label>
319
			</p>
320
		<?php endif;
321
	}
322
323
	function broken_connection( $service_name, $id ) { ?>
324
		<div id="thickbox-content">
325
			<div class='error'>
326
				<p><?php printf( __( 'There was a problem connecting to %s. Please disconnect and try again.', 'jetpack' ), Publicize::get_service_label( $service_name ) ); ?></p>
327
			</div>
328
		</div><?php
329
	}
330
331
	public static function options_page_other( $service_name ) {
332
		// Nonce check
333
		check_admin_referer( "options_page_{$service_name}_" . $_REQUEST['connection'] );
334
		?>
335
		<div id="thickbox-content">
336
			<?php
337
			ob_start();
338
			Publicize_UI::connected_notice( $service_name );
339
			$update_notice = ob_get_clean();
340
			if ( ! empty( $update_notice ) )
341
				echo $update_notice;
342
			?>
343
344
			<?php Publicize_UI::global_checkbox( $service_name, $_REQUEST['connection'] ); ?>
345
346
			<p style="text-align: center;">
347
				<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'] ) ?>" />
348
			</p> <br />
349
		</div>
350
		<?php
351
	}
352
353
	/**
354
	* CSS for styling the publicize message box and counter that displays on the post page.
355
	* There is also some JavaScript for length counting and some basic display effects.
356
	*/
357
	function post_page_metabox_assets() {
358
		global $post;
359
		$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...
360
361
		$default_prefix = $this->publicize->default_prefix;
362
		$default_prefix = preg_replace( '/%([0-9])\$s/', "' + %\\1\$s + '", esc_js( $default_prefix ) );
363
364
		$default_message = $this->publicize->default_message;
365
		$default_message = preg_replace( '/%([0-9])\$s/', "' + %\\1\$s + '", esc_js( $default_message ) );
366
367
		$default_suffix = $this->publicize->default_suffix;
368
		$default_suffix = preg_replace( '/%([0-9])\$s/', "' + %\\1\$s + '", esc_js( $default_suffix ) ); ?>
369
370
<script type="text/javascript">
371
jQuery( function($) {
372
	var wpasTitleCounter    = $( '#wpas-title-counter' ),
373
		wpasTwitterCheckbox = $( '.wpas-submit-twitter' ).length,
374
		wpasTitle = $('#wpas-title').keyup( function() {
375
		var length = wpasTitle.val().length;
376
		wpasTitleCounter.text( length );
377
		if ( wpasTwitterCheckbox && length > 256 ) {
378
			wpasTitleCounter.addClass( 'wpas-twitter-length-limit' );
379
		} else {
380
			wpasTitleCounter.removeClass( 'wpas-twitter-length-limit' );
381
		}
382
		} ),
383
		authClick = false;
384
385
	$('#publicize-disconnected-form-show').click( function() {
386
		$('#publicize-form').slideDown( 'fast' );
387
		$(this).hide();
388
	} );
389
390
	$('#publicize-disconnected-form-hide').click( function() {
391
		$('#publicize-form').slideUp( 'fast' );
392
		$('#publicize-disconnected-form-show').show();
393
	} );
394
395
	$('#publicize-form-edit').click( function() {
396
		$('#publicize-form').slideDown( 'fast', function() {
397
			wpasTitle.focus();
398
			if ( !wpasTitle.text() ) {
399
				var url = $('#shortlink').length ? $('#shortlink').val() : '';
400
401
				var defaultMessage = $.trim( '<?php printf( $default_prefix, 'url' ); printf( $default_message, '$("#title").val()', 'url' ); printf( $default_suffix, 'url' ); ?>' );
0 ignored issues
show
Coding Style introduced by
It is generally recommended to place each PHP statement on a line by itself.

Let’s take a look at an example:

// Bad
$a = 5; $b = 6; $c = 7;

// Good
$a = 5;
$b = 6;
$c = 7;
Loading history...
402
403
				wpasTitle.append( defaultMessage.replace( /<[^>]+>/g,'') );
404
405
				var selBeg = defaultMessage.indexOf( $("#title").val() );
406
				if ( selBeg < 0 ) {
407
					selBeg = 0;
408
					selEnd = 0;
409
				} else {
410
					selEnd = selBeg + $("#title").val().length;
411
				}
412
413
				var domObj = wpasTitle.get(0);
414
				if ( domObj.setSelectionRange ) {
415
					domObj.setSelectionRange( selBeg, selEnd );
416
				} else if ( domObj.createTextRange ) {
417
					var r = domObj.createTextRange();
418
					r.moveStart( 'character', selBeg );
419
					r.moveEnd( 'character', selEnd );
420
					r.select();
421
				}
422
			}
423
			wpasTitle.keyup();
424
		} );
425
		$('#publicize-defaults').hide();
426
		$(this).hide();
427
		return false;
428
	} );
429
430
	$('#publicize-form-hide').click( function() {
431
		var newList = $.map( $('#publicize-form').slideUp( 'fast' ).find( ':checked' ), function( el ) {
432
			return $.trim( $(el).parent( 'label' ).text() );
433
		} );
434
		$('#publicize-defaults').html( '<strong>' + newList.join( '</strong>, <strong>' ) + '</strong>' ).show();
435
		$('#publicize-form-edit').show();
436
		return false;
437
	} );
438
439
	$('.authorize-link').click( function() {
440
		if ( authClick ) {
441
			return false;
442
		}
443
		authClick = true;
444
		$(this).after( '<img src="images/loading.gif" class="alignleft" style="margin: 0 .5em" />' );
445
		$.ajaxSetup( { async: false } );
446
447
		if ( window.wp && window.wp.autosave ) {
448
			window.wp.autosave.server.triggerSave();
449
		} else {
450
			autosave();
451
		}
452
453
		return true;
454
	} );
455
456
	$( '.pub-service' ).click( function() {
457
		var service = $(this).data( 'service' ),
458
			fakebox = '<input id="wpas-submit-' + service + '" type="hidden" value="1" name="wpas[submit][' + service + ']" />';
459
		$( '#add-publicize-check' ).append( fakebox );
460
	} );
461
462
	publicizeConnTestStart = function() {
463
		$( '#pub-connection-tests' )
464
			.removeClass( 'below-h2' )
465
			.removeClass( 'error' )
466
			.removeClass( 'publicize-token-refresh-message' )
467
			.addClass( 'test-in-progress' )
468
			.html( '' );
469
		$.post( ajaxurl, { action: 'test_publicize_conns' }, publicizeConnTestComplete );
470
	}
471
472
	publicizeConnRefreshClick = function( event ) {
473
		event.preventDefault();
474
		var popupURL = event.currentTarget.href;
475
		var popupTitle = event.currentTarget.title;
476
		// open a popup window
477
		// when it is closed, kick off the tests again
478
		var popupWin = window.open( popupURL, popupTitle, '' );
479
		var popupWinTimer= window.setInterval( function() {
480
			if ( popupWin.closed !== false ) {
481
				window.clearInterval( popupWinTimer );
482
				publicizeConnTestStart();
483
			}
484
		}, 500 );
485
	}
486
487
	publicizeConnTestComplete = function( response ) {
488
		var testsSelector = $( '#pub-connection-tests' );
489
		testsSelector
490
			.removeClass( 'test-in-progress' )
491
			.removeClass( 'below-h2' )
492
			.removeClass( 'error' )
493
			.removeClass( 'publicize-token-refresh-message' )
494
			.html( '' );
495
496
		// If any of the tests failed, show some stuff
497
		var somethingShownAlready = false;
498
		var facebookNotice = false;
499
		$.each( response.data, function( index, testResult ) {
500
501
			// find the li for this connection
502
			if ( ! testResult.connectionTestPassed && testResult.userCanRefresh ) {
503
				if ( ! somethingShownAlready ) {
504
					testsSelector
505
						.addClass( 'below-h2' )
506
						.addClass( 'error' )
507
						.addClass( 'publicize-token-refresh-message' )
508
						.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>" );
509
					somethingShownAlready = true;
510
				}
511
512
				if ( testResult.userCanRefresh ) {
513
					testsSelector.append( '<p/>' );
514
					$( '<a/>', {
515
						'class'  : 'pub-refresh-button button',
516
						'title'  : testResult.refreshText,
517
						'href'   : testResult.refreshURL,
518
						'text'   : testResult.refreshText,
519
						'target' : '_refresh_' + testResult.serviceName
520
					} )
521
						.appendTo( testsSelector.children().last() )
522
						.click( publicizeConnRefreshClick );
523
				}
524
			}
525
526
			if( ! testResult.connectionTestPassed && ! testResult.userCanRefresh ) {
527
528
				$( '#wpas-submit-' + testResult.unique_id ).prop( "checked", false ).prop( "disabled", true );
529
				if ( ! facebookNotice ) {
530
					var message = '<p>'
531
						+ testResult.connectionTestMessage
532
						+ '</p><p>'
533
						+ ' <a class="button" href="<?php echo esc_url( admin_url( 'options-general.php?page=sharing' ) ); ?>" rel="noopener noreferrer" target="_blank">'
534
						+ '<?php echo esc_html( __( 'Update Your Sharing Settings' ,'jetpack' ) ); ?>'
535
						+ '</a>'
536
						+ '<p>';
537
538
					testsSelector
539
						.addClass( 'below-h2' )
540
						.addClass( 'error' )
541
						.addClass( 'publicize-token-refresh-message' )
542
						.append( message );
543
					facebookNotice = true;
544
				}
545
546
			}
547
548
549
		} );
550
	}
551
552
	$( document ).ready( function() {
553
		// If we have the #pub-connection-tests div present, kick off the connection test
554
		if ( $( '#pub-connection-tests' ).length ) {
555
			publicizeConnTestStart();
556
		}
557
	} );
558
559
} );
560
</script>
561
562
<style type="text/css">
563
#publicize {
564
	line-height: 1.5;
565
}
566
#publicize ul {
567
	margin: 4px 0 4px 6px;
568
}
569
#publicize li {
570
	margin: 0;
571
}
572
#publicize textarea {
573
	margin: 4px 0 0;
574
	width: 100%
575
}
576
#publicize ul.not-connected {
577
	list-style: square;
578
	padding-left: 1em;
579
}
580
#publicize-title:before {
581
	content: "\f237";
582
	font: normal 20px/1 dashicons;
583
	speak: none;
584
	margin-left: -1px;
585
	padding-right: 3px;
586
	vertical-align: top;
587
	-webkit-font-smoothing: antialiased;
588
	color: #82878c;
589
}
590
.post-new-php .authorize-link, .post-php .authorize-link {
591
	line-height: 1.5em;
592
}
593
.post-new-php .authorize-message, .post-php .authorize-message {
594
	margin-bottom: 0;
595
}
596
#poststuff #publicize .updated p {
597
	margin: .5em 0;
598
}
599
.wpas-twitter-length-limit {
600
	color: red;
601
}
602
</style><?php
603
	}
604
605
	/**
606
	* Controls the metabox that is displayed on the post page
607
	* Allows the user to customize the message that will be sent out to the social network, as well as pick which
608
	* networks to publish to. Also displays the character counter and some other information.
609
	*/
610
	function post_page_metabox() {
611
		global $post;
612
613
		if ( ! $this->publicize->post_type_is_publicizeable( $post->post_type ) )
614
			return;
615
616
		$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...
617
		$services = $this->publicize->get_services( 'connected' );
618
		$available_services = $this->publicize->get_services( 'all' );
619
620
		if ( ! is_array( $available_services ) )
621
			$available_services = array();
622
623
		if ( ! is_array( $services ) )
624
			$services = array();
625
		?>
626
		<div id="publicize" class="misc-pub-section misc-pub-section-last">
627
			<span id="publicize-title">
628
				<?php esc_html_e( 'Publicize:', 'jetpack' ); ?>
629
				<?php if ( 0 < count( $services ) ) : ?>
630
					<?php list( $publicize_form, $active ) = $this->get_metabox_form_connected( $services ); ?>
631
					<span id="publicize-defaults">
632
						<?php foreach ( $active as $item ) : ?>
633
							<strong><?php echo esc_html( $item ); ?></strong>
634
						<?php endforeach; ?>
635
					</span>
636
					<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 />
637
				<?php else : ?>
638
					<?php $publicize_form = $this->get_metabox_form_disconnected( $available_services ); ?>
639
					<strong><?php echo __( 'Not Connected', 'jetpack' ); ?></strong>
640
					<a href="#" id="publicize-disconnected-form-show"><?php esc_html_e( 'Edit', 'jetpack' ); ?></a><br />
641
				<?php endif; ?>
642
			</span>
643
			<?php
644
			/**
645
			 * Filter the Publicize details form.
646
			 *
647
			 * @module publicize
648
			 *
649
			 * @since 2.0.0
650
			 *
651
			 * @param string $publicize_form Publicize Details form appearing above Publish button in the editor.
652
			 */
653
			echo apply_filters( 'publicize_form', $publicize_form );
654
			?>
655
		</div> <?php // #publicize
656
	}
657
658
	private function get_metabox_form_connected( $services ) {
659
		global $post;
660
		$active = array();
661
		ob_start();
662
		?> <div id="publicize-form" class="hide-if-js">
663
			<ul>
664
665
			<?php
666
			// We can set an _all flag to indicate that this post is completely done as
667
			// far as Publicize is concerned. Jetpack uses this approach. All published posts in Jetpack
668
			// have Publicize disabled.
669
			$all_done = get_post_meta( $post->ID, $this->publicize->POST_DONE . 'all', true ) || ( $this->in_jetpack && 'publish' == $post->post_status );
670
671
			// We don't allow Publicizing to the same external id twice, to prevent spam
672
			$service_id_done = (array) get_post_meta( $post->ID, $this->publicize->POST_SERVICE_DONE, true );
673
674
			foreach ( $services as $name => $connections ) {
675
				foreach ( $connections as $connection ) {
676
					$connection_data = '';
677 View Code Duplication
					if ( method_exists( $connection, 'get_meta' ) )
678
						$connection_data = $connection->get_meta( 'connection_data' );
679
					elseif ( ! empty( $connection['connection_data'] ) )
680
						$connection_data = $connection['connection_data'];
681
682
					/**
683
					 * Filter whether a post should be publicized to a given service.
684
					 *
685
					 * @module publicize
686
					 *
687
					 * @since 2.0.0
688
					 *
689
					 * @param bool true Should the post be publicized to a given service? Default to true.
690
					 * @param int $post->ID Post ID.
691
					 * @param string $name Service name.
692
					 * @param array $connection_data Array of information about all Publicize details for the site.
693
					 */
694
					if ( ! $continue = apply_filters( 'wpas_submit_post?', true, $post->ID, $name, $connection_data ) ) {
695
						continue;
696
					}
697
698 View Code Duplication
					if ( ! empty( $connection->unique_id ) ) {
699
						$unique_id = $connection->unique_id;
700
					} else if ( ! empty( $connection['connection_data']['token_id'] ) ) {
701
						$unique_id = $connection['connection_data']['token_id'];
702
					}
703
704
					// Should we be skipping this one?
705
					$skip = (
706
						(
707
							in_array( $post->post_status, array( 'publish', 'draft', 'future' ) )
708
							&&
709
							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...
710
						)
711
						||
712
						(
713
							is_array( $connection )
714
							&&
715
							(
716
								( isset( $connection['meta']['external_id'] ) && ! empty( $service_id_done[ $name ][ $connection['meta']['external_id'] ] ) )
717
								||
718
								// Jetpack's connection data looks a little different.
719
								( isset( $connection['external_id'] ) && ! empty( $service_id_done[ $name ][ $connection['external_id'] ] ) )
720
							)
721
						)
722
					);
723
724
					// Was this connections (OR, old-format service) already Publicized to?
725
					$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
726
727
					// If this one has already been publicized to, don't let it happen again
728
					$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...
729
					if ( $done ) {
730
						$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...
731
					}
732
733
					// If this is a global connection and this user doesn't have enough permissions to modify
734
					// those connections, don't let them change it
735
					$cmeta = $this->publicize->get_connection_meta( $connection );
736
					$hidden_checkbox = false;
737
					if ( !$done && ( 0 == $cmeta['connection_data']['user_id'] && !current_user_can( $this->publicize->GLOBAL_CAP ) ) ) {
738
						$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...
739
						/**
740
						 * Filters the checkboxes for global connections with non-prilvedged users.
741
						 *
742
						 * @module publicize
743
						 *
744
						 * @since 3.7.0
745
						 *
746
						 * @param bool   $checked Indicates if this connection should be enabled. Default true.
747
						 * @param int    $post->ID ID of the current post
748
						 * @param string $name Name of the connection (Facebook, Twitter, etc)
749
						 * @param array  $connection Array of data about the connection.
750
						 */
751
						$hidden_checkbox = apply_filters( 'publicize_checkbox_global_default', true, $post->ID, $name, $connection );
752
					}
753
754
					// Determine the state of the checkbox (on/off) and allow filtering
755
					$checked = $skip != 1 || $done;
756
					/**
757
					 * Filter the checkbox state of each Publicize connection appearing in the post editor.
758
					 *
759
					 * @module publicize
760
					 *
761
					 * @since 2.0.1
762
					 *
763
					 * @param bool $checked Should the Publicize checkbox be enabled for a given service.
764
					 * @param int $post->ID Post ID.
765
					 * @param string $name Service name.
766
					 * @param array $connection Array of connection details.
767
					 */
768
					$checked = apply_filters( 'publicize_checkbox_default', $checked, $post->ID, $name, $connection );
769
770
					// Force the checkbox to be checked if the post was DONE, regardless of what the filter does
771
					if ( $done ) {
772
						$checked = true;
773
					}
774
					$disabled = false;
775
					// This post has been handled, so disable everything
776
					if ( $all_done ) {
777
						$disabled = ' disabled="disabled"';
778
					}
779
780
					$label = sprintf(
781
						_x( '%1$s: %2$s', 'Service: Account connected as', 'jetpack' ),
782
						esc_html( $this->publicize->get_service_label( $name ) ),
783
						esc_html( $this->publicize->get_display_name( $name, $connection ) )
784
					);
785
786
					if (
787
						$name === 'facebook'
788
					     && ! $this->publicize->is_valid_facebook_connection( $connection )
789
					     && $this->publicize->is_connecting_connection( $connection )
790
					) {
791
						$skip = true;
792
						$disabled = ' disabled="disabled"';
793
						$checked = false;
794
						$hidden_checkbox = false;
795
					}
796
797
					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...
798
						$active[] = $label;
799
					}
800
801
					?>
802
					<li>
803
						<label for="wpas-submit-<?php echo esc_attr( $unique_id ); ?>">
804
							<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
805
								checked( true, $checked );
806
								echo $disabled;
807
							?> />
808
							<?php
809
							if ( $hidden_checkbox ) {
810
								// Need to submit a value to force a global connection to post
811
								echo '<input type="hidden" name="wpas[submit][' . $unique_id . ']" value="1" />';
812
							}
813
							echo esc_html( $label );
814
							?>
815
						</label>
816
					</li>
817
					<?php
818
				}
819
			}
820
821
			if ( $title = get_post_meta( $post->ID, $this->publicize->POST_MESS, true ) ) {
822
				$title = esc_html( $title );
823
			} else {
824
				$title = '';
825
			}
826
			?>
827
828
			</ul>
829
830
			<label for="wpas-title"><?php _e( 'Custom Message:', 'jetpack' ); ?></label>
831
			<span id="wpas-title-counter" class="alignright hide-if-no-js">0</span>
832
833
			<textarea name="wpas_title" id="wpas-title"<?php disabled( $all_done ); ?>><?php echo $title; ?></textarea>
834
835
			<a href="#" class="hide-if-no-js button" id="publicize-form-hide"><?php esc_html_e( 'OK', 'jetpack' ); ?></a>
836
			<input type="hidden" name="wpas[0]" value="1" />
837
838
		</div>
839
		<?php if ( ! $all_done ) : ?>
840
			<div id="pub-connection-tests"></div>
841
		<?php endif; ?>
842
		<?php // #publicize-form
843
844
		return array( ob_get_clean(), $active );
845
	}
846
847
848
	private function get_metabox_form_disconnected( $available_services ) {
849
		ob_start();
850
		?><div id="publicize-form" class="hide-if-js">
851
			<div id="add-publicize-check" style="display: none;"></div>
852
853
			<?php _e( 'Connect to', 'jetpack' ); ?>:
854
855
			<ul class="not-connected">
856
				<?php foreach ( $available_services as $service_name => $service ) : ?>
857
				<li>
858
					<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 ) ); ?>">
859
						<?php echo esc_html( $this->publicize->get_service_label( $service_name ) ); ?>
860
					</a>
861
				</li>
862
				<?php endforeach; ?>
863
			</ul>
864
			<a href="#" class="hide-if-no-js button" id="publicize-disconnected-form-hide"><?php esc_html_e( 'OK', 'jetpack' ); ?></a>
865
		</div><?php // #publicize-form
866
		return ob_get_clean();
867
	}
868
}
869