Completed
Push — try/seperate-publicize-handlin... ( f77f43...05ee48 )
by
unknown
08:54
created

Publicize_UI::get_metabox_form_connected()   F

Complexity

Conditions 33
Paths > 20000

Size

Total Lines 188

Duplication

Lines 9
Ratio 4.79 %

Importance

Changes 0
Metric Value
cc 33
nc 718908
nop 1
dl 9
loc 188
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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