Completed
Push — update/publicize-decouple-ui-2 ( 234a2b )
by
unknown
1433:37 queued 1420:53
created

Publicize_Base::test_publicize_conns()   B

Complexity

Conditions 9
Paths 38

Size

Total Lines 59

Duplication

Lines 4
Ratio 6.78 %

Importance

Changes 0
Metric Value
cc 9
nc 38
nop 0
dl 4
loc 59
rs 7.3389
c 0
b 0
f 0

How to fix   Long Method   

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
abstract class Publicize_Base {
4
5
	/**
6
	* Services that are currently connected to the given user
7
	* through publicize.
8
	*/
9
	public $connected_services = array();
10
11
	/**
12
	* Services that are supported by publicize. They don't
13
	* necessarily need to be connected to the current user.
14
	*/
15
	public $services;
16
17
	/**
18
	* key names for post meta
19
	*/
20
	public $ADMIN_PAGE        = 'wpas';
21
	public $POST_MESS         = '_wpas_mess';
22
	public $POST_SKIP         = '_wpas_skip_'; // connection id appended to indicate that a connection should NOT be publicized to
23
	public $POST_DONE         = '_wpas_done_'; // connection id appended to indicate a connection has already been publicized to
24
	public $USER_AUTH         = 'wpas_authorize';
25
	public $USER_OPT          = 'wpas_';
26
	public $PENDING           = '_publicize_pending'; // ready for Publicize to do its thing
27
	public $POST_SERVICE_DONE = '_publicize_done_external'; // array of external ids where we've Publicized
28
29
	/**
30
	* default pieces of the message used in constructing the
31
	* content pushed out to other social networks
32
	*/
33
34
	public $default_prefix  = '';
35
	public $default_message = '%title%';
36
	public $default_suffix  = ' ';
37
38
	/**
39
	 * What WP capability is require to create/delete global connections?
40
	 * All users with this cap can un-globalize all other global connections, and globalize any of their own
41
	 * Globalized connections cannot be unselected by users without this capability when publishing
42
	 */
43
	public $GLOBAL_CAP = 'edit_others_posts';
44
45
	/**
46
	* Sets up the basics of Publicize
47
	*/
48
	function __construct() {
49
		$this->default_message = self::build_sprintf( array(
50
			/**
51
			 * Filter the default Publicize message.
52
			 *
53
			 * @module publicize
54
			 *
55
			 * @since 2.0.0
56
			 *
57
			 * @param string $this->default_message Publicize's default message. Default is the post title.
58
			 */
59
			apply_filters( 'wpas_default_message', $this->default_message ),
60
			'title',
61
			'url',
62
		) );
63
64
		$this->default_prefix = self::build_sprintf( array(
65
			/**
66
			 * Filter the message prepended to the Publicize custom message.
67
			 *
68
			 * @module publicize
69
			 *
70
			 * @since 2.0.0
71
			 *
72
			 * @param string $this->default_prefix String prepended to the Publicize custom message.
73
			 */
74
			apply_filters( 'wpas_default_prefix', $this->default_prefix ),
75
			'url',
76
		) );
77
78
		$this->default_suffix = self::build_sprintf( array(
79
			/**
80
			 * Filter the message appended to the Publicize custom message.
81
			 *
82
			 * @module publicize
83
			 *
84
			 * @since 2.0.0
85
			 *
86
			 * @param string $this->default_suffix String appended to the Publicize custom message.
87
			 */
88
			apply_filters( 'wpas_default_suffix', $this->default_suffix ),
89
			'url',
90
		) );
91
92
		/**
93
		 * Filter the capability to change global Publicize connection options.
94
		 *
95
		 * All users with this cap can un-globalize all other global connections, and globalize any of their own
96
		 * Globalized connections cannot be unselected by users without this capability when publishing.
97
		 *
98
		 * @module publicize
99
		 *
100
		 * @since 2.2.1
101
		 *
102
		 * @param string $this->GLOBAL_CAP default capability in control of global Publicize connection options. Default to edit_others_posts.
103
		 */
104
		$this->GLOBAL_CAP = apply_filters( 'jetpack_publicize_global_connections_cap', $this->GLOBAL_CAP );
105
106
		// stage 1 and 2 of 3-stage Publicize. Flag for Publicize on creation, save meta,
107
		// then check meta and publicize based on that. stage 3 implemented on wpcom
108
		add_action( 'transition_post_status', array( $this, 'flag_post_for_publicize' ), 10, 3 );
109
		add_action( 'save_post', array( &$this, 'save_meta' ), 20, 2 );
110
111
		// Default checkbox state for each Connection
112
		add_filter( 'publicize_checkbox_default', array( $this, 'publicize_checkbox_default' ), 10, 4 );
113
114
		// Alter the "Post Publish" admin notice to mention the Connections we Publicized to.
115
		add_filter( 'post_updated_messages', array( $this, 'update_published_message' ), 20, 1 );
116
117
		// Connection test callback
118
		add_action( 'wp_ajax_test_publicize_conns', array( $this, 'test_publicize_conns' ) );
119
	}
120
121
/*
122
 * Services: Facebook, Twitter, etc.
123
 */
124
125
	/**
126
	 * Get services for the given blog and user.
127
	 *
128
	 * Can return all available services or just the ones with an active connection.
129
	 *
130
	 * @param string $filter
131
	 *        'all' (default) - Get all services available for connecting
132
	 *        'connected'     - Get all services currently connected
133
	 * @param false|int $_blog_id The blog ID. Use false (default) for the current blog
134
	 * @param false|int $_user_id The user ID. Use false (default) for the current user
135
	 * @return array
136
	 */
137
	abstract function get_services( $filter = 'all', $_blog_id = false, $_user_id = false );
138
139
	/**
140
	 * Does the given user have a connection to the service on the given blog?
141
	 *
142
	 * @param string $service_name 'facebook', 'twitter', etc.
143
	 * @param false|int $_blog_id The blog ID. Use false (default) for the current blog
144
	 * @param false|int $_user_id The user ID. Use false (default) for the current user
145
	 * @return bool
146
	 */
147
	function is_enabled( $service_name, $_blog_id = false, $_user_id = false ) {
148
		if ( !$_blog_id )
0 ignored issues
show
Bug Best Practice introduced by
The expression $_blog_id of type false|integer is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

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

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
149
			$_blog_id = $this->blog_id();
150
151
		if ( !$_user_id )
0 ignored issues
show
Bug Best Practice introduced by
The expression $_user_id of type false|integer is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

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

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
152
			$_user_id = $this->user_id();
153
154
		$connections = $this->get_connections( $service_name, $_blog_id, $_user_id );
155
		return ( is_array( $connections ) && count( $connections ) > 0 ? true : false );
156
	}
157
158
	/**
159
	 * Generates a connection URL.
160
	 *
161
	 * This is the URL, which, when visited by the user, starts the authentication
162
	 * process required to forge a connection.
163
	 *
164
	 * @param string $service_name 'facebook', 'twitter', etc.
165
	 * @return string
166
	 */
167
	abstract function connect_url( $service_name );
168
169
	/**
170
	 * Generates a Connection refresh URL.
171
	 *
172
	 * This is the URL, which, when visited by the user, re-authenticates their
173
	 * connection to the service.
174
	 *
175
	 * @param string $service_name 'facebook', 'twitter', etc.
176
	 * @return string
177
	 */
178
	abstract function refresh_url( $service_name );
179
180
	/**
181
	 * Generates a disconnection URL.
182
	 *
183
	 * This is the URL, which, when visited by the user, breaks their connection
184
	 * with the service.
185
	 *
186
	 * @param string $service_name 'facebook', 'twitter', etc.
187
	 * @param string $connection_id Connection ID
188
	 * @return string
189
	 */
190
	abstract function disconnect_url( $service_name, $connection_id );
191
192
	/**
193
	 * Returns a display name for the Service
194
	 *
195
	 * @param string $service_name 'facebook', 'twitter', etc.
196
	 * @return string
197
	 */
198
	public static function get_service_label( $service_name ) {
199
		switch ( $service_name ) {
200
			case 'linkedin':
201
				return 'LinkedIn';
202
				break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
203
			case 'google_plus':
204
				return  'Google+';
205
				break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
206
			case 'twitter':
207
			case 'facebook':
208
			case 'tumblr':
209
			default:
210
				return ucfirst( $service_name );
211
				break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
212
		}
213
	}
214
215
/*
216
 * Connections: For each Service, there can be multiple connections
217
 * for a given user. For example, one user could be connected to Twitter
218
 * as both @jetpack and as @wordpressdotcom
219
 *
220
 * For historical reasons, Connections are represented as an object
221
 * on WordPress.com and as an array in Jetpack.
222
 */
223
224
	/**
225
	 * Get the active Connections of a Service
226
	 *
227
	 * @param string $service_name 'facebook', 'twitter', etc.
228
	 * @param false|int $_blog_id The blog ID. Use false (default) for the current blog
229
	 * @param false|int $_user_id The user ID. Use false (default) for the current user
230
	 * @return false|object[]|array[] false if no connections exist
231
	 */
232
	abstract function get_connections( $service_name, $_blog_id = false, $_user_id = false );
233
234
	/**
235
	 * Get a single Connection of a Service
236
	 *
237
	 * @param string $service_name 'facebook', 'twitter', etc.
238
	 * @param string $connection_id Connection ID
239
	 * @param false|int $_blog_id The blog ID. Use false (default) for the current blog
240
	 * @param false|int $_user_id The user ID. Use false (default) for the current user
241
	 * @return false|object[]|array[] false if no connections exist
242
	 */
243
	abstract function get_connection( $service_name, $connection_id, $_blog_id = false, $_user_id = false );
244
245
	/**
246
	 * Get the Connection ID.
247
	 *
248
	 * Note that this is different than the Connection's uniqueid.
249
	 *
250
	 * Via a quirk of history, ID is globally unique and unique_id
251
	 * is only unique per site.
252
	 *
253
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
254
	 * @return string
255
	 */
256
	abstract function get_connection_id( $connection );
257
258
	/**
259
	 * Get the Connection unique_id
260
	 *
261
	 * Note that this is different than the Connections ID.
262
	 *
263
	 * Via a quirk of history, ID is globally unique and unique_id
264
	 * is only unique per site.
265
	 *
266
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
267
	 * @return string
268
	 */
269
	abstract function get_connection_unique_id( $connection );
270
271
	/**
272
	 * Get the Connection's Meta data
273
	 *
274
	 * @param object|array Connection
275
	 * @return array Connection Meta
276
	 */
277
	abstract function get_connection_meta( $connection );
278
279
	/**
280
	 * Disconnect a Connection
281
	 *
282
	 * @param string $service_name 'facebook', 'twitter', etc.
283
	 * @param string $connection_id Connection ID
284
	 * @param false|int $_blog_id The blog ID. Use false (default) for the current blog
285
	 * @param false|int $_user_id The user ID. Use false (default) for the current user
286
	 * @param bool $force_delete Whether to skip permissions checks
287
	 * @return false|void False on failure. Void on success.
288
	 */
289
	abstract function disconnect( $service_name, $connection_id, $_blog_id = false, $_user_id = false, $force_delete = false );
290
291
	/**
292
	 * Globalizes a Connection
293
	 *
294
	 * @param string $connection_id Connection ID
295
	 * @return bool Falsey on failure. Truthy on success.
296
	 */
297
	abstract function globalize_connection( $connection_id );
298
299
	/**
300
	 * Unglobalizes a Connection
301
	 *
302
	 * @param string $connection_id Connection ID
303
	 * @return bool Falsey on failure. Truthy on success.
304
	 */
305
	abstract function unglobalize_connection( $connection_id );
306
307
	/**
308
	 * Returns an external URL to the Connection's profile
309
	 *
310
	 * @param string $service_name 'facebook', 'twitter', etc.
311
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
312
	 * @return false|string False on failure. URL on success.
313
	 */
314
	function get_profile_link( $service_name, $connection ) {
315
		$cmeta = $this->get_connection_meta( $connection );
316
317
		if ( isset( $cmeta['connection_data']['meta']['link'] ) ) {
318
			if ( 'facebook' == $service_name && 0 === strpos( parse_url( $cmeta['connection_data']['meta']['link'], PHP_URL_PATH ), '/app_scoped_user_id/' ) ) {
319
				// App-scoped Facebook user IDs are not usable profile links
320
				return false;
321
			}
322
323
			return $cmeta['connection_data']['meta']['link'];
324 View Code Duplication
		} elseif ( 'facebook' == $service_name && isset( $cmeta['connection_data']['meta']['facebook_page'] ) ) {
325
			return 'https://facebook.com/' . $cmeta['connection_data']['meta']['facebook_page'];
326
		} elseif ( 'tumblr' == $service_name && isset( $cmeta['connection_data']['meta']['tumblr_base_hostname'] ) ) {
327
			 return 'http://' . $cmeta['connection_data']['meta']['tumblr_base_hostname'];
328
		} elseif ( 'twitter' == $service_name ) {
329
			return 'https://twitter.com/' . substr( $cmeta['external_display'], 1 ); // Has a leading '@'
330 View Code Duplication
		} elseif ( 'google_plus' == $service_name && isset( $cmeta['connection_data']['meta']['google_plus_page'] ) ) {
331
			return 'https://plus.google.com/' . $cmeta['connection_data']['meta']['google_plus_page'];
332
		} elseif ( 'google_plus' == $service_name ) {
333
			return 'https://plus.google.com/' . $cmeta['external_id'];
334
		} else if ( 'linkedin' == $service_name ) {
335
			if ( !isset( $cmeta['connection_data']['meta']['profile_url'] ) ) {
336
				return false;
337
			}
338
339
			$profile_url_query = parse_url( $cmeta['connection_data']['meta']['profile_url'], PHP_URL_QUERY );
340
			wp_parse_str( $profile_url_query, $profile_url_query_args );
0 ignored issues
show
Bug introduced by
The variable $profile_url_query_args does not exist. Did you mean $profile_url_query?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
341
			if ( isset( $profile_url_query_args['key'] ) ) {
0 ignored issues
show
Bug introduced by
The variable $profile_url_query_args does not exist. Did you mean $profile_url_query?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
342
				$id = $profile_url_query_args['key'];
343
			} elseif ( isset( $profile_url_query_args['id'] ) ) {
0 ignored issues
show
Bug introduced by
The variable $profile_url_query_args does not exist. Did you mean $profile_url_query?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
344
				$id = $profile_url_query_args['id'];
345
			} else {
346
				return false;
347
			}
348
349
			return esc_url_raw( add_query_arg( 'id', urlencode( $id ), 'http://www.linkedin.com/profile/view' ) );
350
		} else {
351
			return false; // no fallback. we just won't link it
352
		}
353
	}
354
355
	/**
356
	 * Returns a display name for the Connection
357
	 *
358
	 * @param string $service_name 'facebook', 'twitter', etc.
359
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
360
	 * @return string
361
	 */
362
	function get_display_name( $service_name, $connection ) {
363
		$cmeta = $this->get_connection_meta( $connection );
364
365
		if ( isset( $cmeta['connection_data']['meta']['display_name'] ) ) {
366
			return $cmeta['connection_data']['meta']['display_name'];
367 View Code Duplication
		} elseif ( $service_name == 'tumblr' && isset( $cmeta['connection_data']['meta']['tumblr_base_hostname'] ) ) {
368
			 return $cmeta['connection_data']['meta']['tumblr_base_hostname'];
369
		} elseif ( $service_name == 'twitter' ) {
370
			return $cmeta['external_display'];
371
		} else {
372
			$connection_display = $cmeta['external_display'];
373
			if ( empty( $connection_display ) )
374
				$connection_display = $cmeta['external_name'];
375
			return $connection_display;
376
		}
377
	}
378
379
	/**
380
	 * Whether the user needs to select additional options after connecting
381
	 *
382
	 * @param string $service_name 'facebook', 'twitter', etc.
383
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
384
	 * @return bool
385
	 */
386
	function show_options_popup( $service_name, $connection ) {
387
		$cmeta = $this->get_connection_meta( $connection );
388
389
		// always show if no selection has been made for facebook
390
		if ( 'facebook' == $service_name && empty( $cmeta['connection_data']['meta']['facebook_profile'] ) && empty( $cmeta['connection_data']['meta']['facebook_page'] ) )
391
			return true;
392
393
		// always show if no selection has been made for tumblr
394
		if ( 'tumblr' == $service_name && empty ( $cmeta['connection_data']['meta']['tumblr_base_hostname'] ) )
395
			return true;
396
397
		// if we have the specific connection info..
398
		if ( isset( $_GET['id'] ) ) {
399
			if ( $cmeta['connection_data']['id'] == $_GET['id'] )
400
				return true;
401
		} else {
402
			// otherwise, just show if this is the completed step / first load
403
			if ( !empty( $_GET['action'] ) && 'completed' == $_GET['action'] && !empty( $_GET['service'] ) && $service_name == $_GET['service'] && ! in_array( $_GET['service'], array( 'facebook', 'tumblr' ) ) )
404
				return true;
405
		}
406
407
		return false;
408
	}
409
410
	/**
411
	 * Whether the Connection is "valid" wrt Facebook's requirements.
412
	 *
413
	 * Must be connected to a Page (not a Profile).
414
	 * (Also returns true if we're in the middle of the connection process)
415
	 *
416
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
417
	 * @return bool
418
	 */
419
	function is_valid_facebook_connection( $connection ) {
420
		if ( $this->is_connecting_connection( $connection ) ) {
421
			return true;
422
		}
423
		$connection_meta = $this->get_connection_meta( $connection );
424
		$connection_data = $connection_meta['connection_data'];
425
		return isset( $connection_data[ 'meta' ][ 'facebook_page' ] );
426
	}
427
428
	/**
429
	 * Whether the Connection currently being connected
430
	 *
431
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
432
	 * @return bool
433
	 */
434
	function is_connecting_connection( $connection ) {
435
		$connection_meta = $this->get_connection_meta( $connection );
436
		$connection_data = $connection_meta['connection_data'];
437
		return isset( $connection_data[ 'meta' ]['options_responses'] );
438
	}
439
440
	/**
441
	 * AJAX Handler to run connection tests on all Connections
442
	 * @return void
443
	 */
444
	function test_publicize_conns() {
445
		$test_results = array();
446
447
		foreach ( (array) $this->get_services( 'connected' ) as $service_name => $connections ) {
448
			foreach ( $connections as $connection ) {
449
450
				$id = $this->get_connection_id( $connection );
451
452
				$connection_test_passed = true;
453
				$connection_test_message = __( 'This connection is working correctly.' , 'jetpack' );
454
				$user_can_refresh = false;
455
				$refresh_text = '';
456
				$refresh_url = '';
457
458
				$connection_test_result = true;
459
				if ( method_exists( $this, 'test_connection' ) ) {
460
					$connection_test_result = $this->test_connection( $service_name, $connection );
461
				}
462
463
				if ( is_wp_error( $connection_test_result ) ) {
464
					$connection_test_passed = false;
465
					$connection_test_message = $connection_test_result->get_error_message();
466
					$error_data = $connection_test_result->get_error_data();
467
468
					$user_can_refresh = $error_data['user_can_refresh'];
469
					$refresh_text = $error_data['refresh_text'];
470
					$refresh_url = $error_data['refresh_url'];
471
				}
472
				// Mark facebook profiles as deprecated
473
				if ( 'facebook' === $service_name ) {
474
					if ( ! $this->is_valid_facebook_connection( $connection ) ) {
475
						$connection_test_passed = false;
476
						$user_can_refresh = false;
477
						$connection_test_message = __( 'Facebook no longer supports Publicize connections to Facebook Profiles, but you can still connect Facebook Pages. Please select a Facebook Page to publish updates to.' );
478
					}
479
				}
480
481
				$unique_id = null;
482 View Code Duplication
				if ( ! empty( $connection->unique_id ) ) {
483
					$unique_id = $connection->unique_id;
484
				} else if ( ! empty( $connection['connection_data']['token_id'] ) ) {
485
					$unique_id = $connection['connection_data']['token_id'];
486
				}
487
488
				$test_results[] = array(
489
					'connectionID'          => $id,
490
					'serviceName'           => $service_name,
491
					'connectionTestPassed'  => $connection_test_passed,
492
					'connectionTestMessage' => esc_attr( $connection_test_message ),
493
					'userCanRefresh'        => $user_can_refresh,
494
					'refreshText'           => esc_attr( $refresh_text ),
495
					'refreshURL'            => $refresh_url,
496
					'unique_id'             => $unique_id,
497
				);
498
			}
499
		}
500
501
		wp_send_json_success( $test_results );
502
	}
503
504
	/**
505
	 * Run the connection test for the Connection
506
	 *
507
	 * @param string $service_name 'facebook', 'twitter', etc.
508
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
509
	 * @return WP_Error|true WP_Error on failure. True on success
510
	 */
511
	abstract function test_connection( $service_name, $connection );
512
513
	/**
514
	 * Retrieves current list of connections and applies filters.
515
	 *
516
	 * Retrieves current available connections and checks if the connections
517
	 * have already been used to share current post. Finally, the checkbox
518
	 * form UI fields are calculated. This function exposes connection form
519
	 * data directly as array so it can be retrieved for static HTML generation
520
	 * or JSON consumption.
521
	 *
522
	 * @since 6.5.0
523
	 *
524
	 * @param integer $selected_post_id Optional. Post ID to query connection status for.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $selected_post_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
525
	 *
526
	 * @return array {
527
	 *     Array of UI setup data for connection list form.
528
	 *
529
	 *     @type string 'unique_id'    ID string representing connection
530
	 *     @type string 'service_name' Slug of the connection's service (facebook, twitter, ...)
531
	 *     @type string 'label'        Service Label and Connection's Username: "Twitter: @jetpack"
532
	 *     @type bool   'enabled'      Default value for the connection (e.g., for a checkbox).
533
	 *     @type bool   'done'         Has this connection already been publicized to?
534
	 *     @type bool   'toggleable'   Is the user allowed to change the value for the connection?
535
	 *     @type bool   'global'       Is this connection a global one?
536
	 *     @type bool   'visible'      Should the connection be shown to the user?
537
	 * }
538
	 */
539
	public function get_filtered_connection_data( $selected_post_id = null ) {
540
		$connection_list = array();
541
542
		$post = get_post( $selected_post_id ); // Defaults to current post if $post_id is null.
543
		// Handle case where there is no current post.
544
		if ( ! empty( $post ) ) {
545
			$post_id = $post->ID;
546
		} else {
547
			$post_id = null;
548
		}
549
550
		$services = $this->get_services( 'connected' );
551
		$all_done = $this->done_sharing_post( $post_id );
552
553
		// We don't allow Publicizing to the same external id twice, to prevent spam.
554
		$service_id_done = (array) get_post_meta( $post_id, $this->POST_SERVICE_DONE, true );
555
556
		foreach ( $services as $service_name => $connections ) {
557
			foreach ( $connections as $connection ) {
558
				$connection_meta = $this->get_connection_meta( $connection );
559
				$connection_data = $connection_meta['connection_data'];
560
561
				$unique_id = $this->get_connection_unique_id( $connection );
562
563
564
				// Was this connection (OR, old-format service) already Publicized to?
565
				$done = ! empty( $post ) && (
566
					// New flags
567
					1 == get_post_meta( $post->ID, $this->POST_DONE . $unique_id, true )
568
					||
569
					// old flags
570
					1 == get_post_meta( $post->ID, $this->POST_DONE . $service_name, true )
571
				);
572
573
				/**
574
				 * Filter whether a post should be publicized to a given service.
575
				 *
576
				 * @module publicize
577
				 *
578
				 * @since 2.0.0
579
				 *
580
				 * @param bool true Should the post be publicized to a given service? Default to true.
581
				 * @param int $post_id Post ID.
582
				 * @param string $service_name Service name.
583
				 * @param array $connection_data Array of information about all Publicize details for the site.
584
				 */
585
				if ( ! apply_filters( 'wpas_submit_post?', true, $post_id, $service_name, $connection_data ) ) {
586
					continue;
587
				}
588
589
				// Should we be skipping this one?
590
				$skip = (
591
					(
592
						! empty( $post )
593
						&&
594
						in_array( $post->post_status, array( 'publish', 'draft', 'future' ) )
595
						&&
596
						(
597
							// New flags
598
							get_post_meta( $post_id, $this->POST_SKIP . $unique_id, true )
599
							||
600
							// Old flags
601
							get_post_meta( $post->ID, $this->POST_SKIP . $service_name )
602
						)
603
					)
604
					||
605
					(
606
						is_array( $connection )
607
						&&
608
						isset( $connection_meta['external_id'] ) && ! empty( $service_id_done[ $service_name ][ $connection_meta['external_id'] ] )
609
					)
610
				);
611
612
				// If this one has already been publicized to, don't let it happen again.
613
				$toggleable = ! $done && ! $all_done;
614
615
				// Determine the state of the checkbox (on/off) and allow filtering.
616
				$enabled = $done || ! $skip;
617
				/**
618
				 * Filter the checkbox state of each Publicize connection appearing in the post editor.
619
				 *
620
				 * @module publicize
621
				 *
622
				 * @since 2.0.1
623
				 *
624
				 * @param bool $enabled Should the Publicize checkbox be enabled for a given service.
625
				 * @param int $post_id Post ID.
626
				 * @param string $service_name Service name.
627
				 * @param array $connection Array of connection details.
628
				 */
629
				$enabled = apply_filters( 'publicize_checkbox_default', $enabled, $post_id, $service_name, $connection );
630
631
				/**
632
				 * If this is a global connection and this user doesn't have enough permissions to modify
633
				 * those connections, don't let them change it.
634
				 */
635
				$visible = true;
636
				if ( ! $done && ( 0 == $connection_data['user_id'] && ! current_user_can( $this->GLOBAL_CAP ) ) ) {
637
					$toggleable = false;
638
					$visible = false;
639
640
					/**
641
					 * Filters the checkboxes for global connections with non-prilvedged users.
642
					 *
643
					 * @module publicize
644
					 *
645
					 * @since 3.7.0
646
					 *
647
					 * @param bool   $enabled Indicates if this connection should be enabled. Default true.
648
					 * @param int    $post_id ID of the current post
649
					 * @param string $service_name Name of the connection (Facebook, Twitter, etc)
650
					 * @param array  $connection Array of data about the connection.
651
					 */
652
					$enabled = apply_filters( 'publicize_checkbox_global_default', true, $post_id, $service_name, $connection );
653
				}
654
655
				// Force the checkbox to be checked if the post was DONE, regardless of what the filter does.
656
				if ( $done ) {
657
					$enabled = true;
658
				}
659
660
				$label  = sprintf(
661
					/* translators: %1$s: Service Name (Facebook, Twitter, ...), %2$s: Username on Service (@jetpack, ...) */
662
					__( '%1$s: %2$s', 'jetpack' ),
663
					$this->get_service_label( $service_name ),
664
					$this->get_display_name( $service_name, $connection )
665
				);
666
667
				$connection_list[] = array(
668
					'unique_id'    => $unique_id,
669
					'service_name' => $service_name,
670
					'label'        => $label,
671
672
					'enabled'      => $enabled,
673
					'done'         => $done,
674
					'toggleable'   => $toggleable,
675
					'global'       => 0 == $connection_data['user_id'],
676
					'visible'      => $visible,
677
				);
678
			}
679
		}
680
681
		return $connection_list;
682
	}
683
684
	/**
685
	 * Checks if post has already been shared by Publicize in the past.
686
	 *
687
	 * We can set an _all flag to indicate that this post is completely done as
688
	 * far as Publicize is concerned. Jetpack uses this approach. All published posts in Jetpack
689
	 * have Publicize disabled.
690
	 *
691
	 * @since 6.5.0
692
	 *
693
	 * @global Publicize_UI $publicize_ui UI instance that contains the 'in_jetpack' property
694
	 *
695
	 * @param integer $post_id Optional. Post ID to query connection status for: will use current post if missing.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $post_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
696
	 *
697
	 * @return bool True if post has already been shared by Publicize, false otherwise.
698
	 */
699
	public function done_sharing_post( $post_id = null ) {
700
		global $publicize_ui;
701
		$post = get_post( $post_id ); // Defaults to current post if $post_id is null.
702
		if ( is_null( $post ) ) {
703
			return false;
704
		}
705
		return get_post_meta( $post->ID, $this->POST_DONE . 'all', true ) || ( $publicize_ui->in_jetpack && 'publish' == $post->post_status );
706
	}
707
708
	/**
709
	 * Retrieves full list of available Publicize connection services.
710
	 *
711
	 * Retrieves current available publicize service connections
712
	 * with associated labels and URLs.
713
	 *
714
	 * @since 6.5.0
715
	 *
716
	 * @return array {
717
	 *     Array of UI service connection data for all services
718
	 *
719
	 *     @type string 'name'  Name of service.
720
	 *     @type string 'label' Display label for service.
721
	 *     @type string 'url'   URL for adding connection to service.
722
	 * }
723
	 */
724
	function get_available_service_data() {
725
		$available_services     = $this->get_services( 'all' );
726
		$available_service_data = array();
727
728
		foreach ( $available_services as $service_name => $service ) {
729
			$available_service_data[] = array(
730
				'name'  => $service_name,
731
				'label' => $this->get_service_label( $service_name ),
732
				'url'   => $this->connect_url( $service_name ),
733
			);
734
		}
735
736
		return $available_service_data;
737
	}
738
739
/*
740
 * Site Data
741
 */
742
743
	function user_id() {
744
		return get_current_user_id();
745
	}
746
747
	function blog_id() {
748
		return get_current_blog_id();
749
	}
750
751
/*
752
 * Posts
753
 */
754
755
	/**
756
	 * Checks old and new status to see if the post should be flagged as
757
	 * ready to Publicize.
758
	 *
759
	 * Attached to the `transition_post_status` filter.
760
	 *
761
	 * @param string $new_status
762
	 * @param string $old_status
763
	 * @param WP_Post $post
764
	 * @return void
765
	 */
766
	abstract function flag_post_for_publicize( $new_status, $old_status, $post );
767
768
	/**
769
	 * Fires when a post is saved, checks conditions and saves state in postmeta so that it
770
	 * can be picked up later by @see ::publicize_post() on WordPress.com codebase.
771
	 *
772
	 * Attached to the `save_post` action.
773
	 *
774
	 * @param int $post_id
775
	 * @param WP_Post $post
776
	 * @return void
777
	 */
778
	function save_meta( $post_id, $post ) {
779
		$cron_user = null;
780
		$submit_post = true;
781
782
		if ( ! $this->post_type_is_publicizeable( $post->post_type ) )
783
			return;
784
785
		// Don't Publicize during certain contexts:
786
787
		// - import
788
		if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING  ) {
789
			$submit_post = false;
790
		}
791
792
		// - on quick edit, autosave, etc but do fire on p2, quickpress, and instapost ajax
793
		if (
794
			defined( 'DOING_AJAX' )
795
		&&
796
			DOING_AJAX
797
		&&
798
			!did_action( 'p2_ajax' )
799
		&&
800
			!did_action( 'wp_ajax_json_quickpress_post' )
801
		&&
802
			!did_action( 'wp_ajax_instapost_publish' )
803
		&&
804
			!did_action( 'wp_ajax_post_reblog' )
805
		&&
806
			!did_action( 'wp_ajax_press-this-save-post' )
807
		) {
808
			$submit_post = false;
809
		}
810
811
		// - bulk edit
812
		if ( isset( $_GET['bulk_edit'] ) ) {
813
			$submit_post = false;
814
		}
815
816
		// - API/XML-RPC Test Posts
817
		if (
818
			(
819
				defined( 'XMLRPC_REQUEST' )
820
			&&
821
				XMLRPC_REQUEST
822
			||
823
				defined( 'APP_REQUEST' )
824
			&&
825
				APP_REQUEST
826
			)
827
		&&
828
			0 === strpos( $post->post_title, 'Temporary Post Used For Theme Detection' )
829
		) {
830
			$submit_post = false;
831
		}
832
833
		// only work with certain statuses (avoids inherits, auto drafts etc)
834
		if ( !in_array( $post->post_status, array( 'publish', 'draft', 'future' ) ) ) {
835
			$submit_post = false;
836
		}
837
838
		// don't publish password protected posts
839
		if ( '' !== $post->post_password ) {
840
			$submit_post = false;
841
		}
842
843
		// Did this request happen via wp-admin?
844
		$from_web = isset( $_SERVER['REQUEST_METHOD'] )
845
			&&
846
			'post' == strtolower( $_SERVER['REQUEST_METHOD'] )
847
			&&
848
			isset( $_POST[$this->ADMIN_PAGE] );
849
850
		if ( ( $from_web || defined( 'POST_BY_EMAIL' ) ) && isset( $_POST['wpas_title'] ) ) {
851
			if ( empty( $_POST['wpas_title'] ) ) {
852
				delete_post_meta( $post_id, $this->POST_MESS );
853
			} else {
854
				update_post_meta( $post_id, $this->POST_MESS, trim( stripslashes( $_POST['wpas_title'] ) ) );
855
			}
856
		}
857
858
		// change current user to provide context for get_services() if we're running during cron
859
		if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
860
			$cron_user = (int) $GLOBALS['user_ID'];
861
			wp_set_current_user( $post->post_author );
862
		}
863
864
		/**
865
		 * In this phase, we mark connections that we want to SKIP. When Publicize is actually triggered,
866
		 * it will Publicize to everything *except* those marked for skipping.
867
		 */
868
		foreach ( (array) $this->get_services( 'connected' ) as $service_name => $connections ) {
869
			foreach ( $connections as $connection ) {
870
				$connection_data = '';
871
				if ( method_exists( $connection, 'get_meta' ) )
872
					$connection_data = $connection->get_meta( 'connection_data' );
873
				elseif ( ! empty( $connection['connection_data'] ) )
874
					$connection_data = $connection['connection_data'];
875
876
				/** This action is documented in modules/publicize/ui.php */
877
				if ( false == apply_filters( 'wpas_submit_post?', $submit_post, $post_id, $service_name, $connection_data ) ) {
878
					delete_post_meta( $post_id, $this->PENDING );
879
					continue;
880
				}
881
882 View Code Duplication
				if ( !empty( $connection->unique_id ) )
883
					$unique_id = $connection->unique_id;
884
				else if ( !empty( $connection['connection_data']['token_id'] ) )
885
					$unique_id = $connection['connection_data']['token_id'];
886
887
				// This was a wp-admin request, so we need to check the state of checkboxes
888
				if ( $from_web ) {
889
					// delete stray service-based post meta
890
					delete_post_meta( $post_id, $this->POST_SKIP . $service_name );
891
892
					// We *unchecked* this stream from the admin page, or it's set to readonly, or it's a new addition
893
					if ( empty( $_POST[$this->ADMIN_PAGE]['submit'][$unique_id] ) ) {
894
						// Also make sure that the service-specific input isn't there.
895
						// If the user connected to a new service 'in-page' then a hidden field with the service
896
						// name is added, so we just assume they wanted to Publicize to that service.
897
						if ( empty( $_POST[$this->ADMIN_PAGE]['submit'][$service_name] ) ) {
898
							// Nothing seems to be checked, so we're going to mark this one to be skipped
899
							update_post_meta( $post_id, $this->POST_SKIP . $unique_id, 1 );
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...
900
							continue;
901
						} else {
902
							// clean up any stray post meta
903
							delete_post_meta( $post_id, $this->POST_SKIP . $unique_id );
904
						}
905
					} else {
906
						// The checkbox for this connection is explicitly checked -- make sure we DON'T skip it
907
						delete_post_meta( $post_id, $this->POST_SKIP . $unique_id );
908
					}
909
				}
910
911
				/**
912
				 * Fires right before the post is processed for Publicize.
913
				 * Users may hook in here and do anything else they need to after meta is written,
914
				 * and before the post is processed for Publicize.
915
				 *
916
				 * @since 2.1.2
917
				 *
918
				 * @param bool $submit_post Should the post be publicized.
919
				 * @param int $post->ID Post ID.
920
				 * @param string $service_name Service name.
921
				 * @param array $connection Array of connection details.
922
				 */
923
				do_action( 'publicize_save_meta', $submit_post, $post_id, $service_name, $connection );
924
			}
925
		}
926
927
		if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
928
			wp_set_current_user( $cron_user );
929
		}
930
931
		// Next up will be ::publicize_post()
932
	}
933
934
	/**
935
	 * Alters the "Post Published" message to include information about where the post
936
	 * was Publicized to.
937
	 *
938
	 * Attached to the `post_updated_messages` filter
939
	 *
940
	 * @param string[] $messages
941
	 * @return string[]
942
	 */
943
	public function update_published_message( $messages ) {
944
		global $post_type, $post_type_object, $post;
945
		if ( ! $this->post_type_is_publicizeable( $post_type ) ) {
946
			return $messages;
947
		}
948
		$view_post_link_html = '';
949
		$viewable = is_post_type_viewable( $post_type_object );
950
		if ( $viewable ) {
951
			$view_text = esc_html__( 'View post' ); // intentionally omitted domain
952
953
			if ( 'jetpack-portfolio' == $post_type ) {
954
				$view_text = esc_html__( 'View project', 'jetpack' );
955
			}
956
957
			$view_post_link_html = sprintf( ' <a href="%1$s">%2$s</a>',
958
				esc_url( get_permalink( $post ) ),
959
				$view_text
960
			);
961
		}
962
963
		$services = $this->get_publicizing_services( $post->ID );
964
		if ( empty( $services ) ) {
965
			return $messages;
966
		}
967
968
		$labels = array();
969
		foreach ( $services as $service_name => $display_names ) {
970
			$labels[] = sprintf(
971
				/* translators: Service name is %1$s, and account name is %2$s. */
972
				esc_html__( '%1$s (%2$s)', 'jetpack' ),
973
				esc_html( $service_name ),
974
				esc_html( implode( ', ', $display_names ) )
975
			);
976
		}
977
978
		$messages['post'][6] = sprintf(
979
			/* translators: %1$s is a comma-separated list of services and accounts. Ex. Facebook (@jetpack), Twitter (@jetpack) */
980
			esc_html__( 'Post published and sharing on %1$s.', 'jetpack' ),
981
			implode( ', ', $labels )
982
		) . $view_post_link_html;
983
984
		if ( $post_type == 'post' && class_exists('Jetpack_Subscriptions' ) ) {
985
			$subscription = Jetpack_Subscriptions::init();
986
			if ( $subscription->should_email_post_to_subscribers( $post ) ) {
987
				$messages['post'][6] = sprintf(
988
					/* translators: %1$s is a comma-separated list of services and accounts. Ex. Facebook (@jetpack), Twitter (@jetpack) */
989
					esc_html__( 'Post published, sending emails to subscribers and sharing post on %1$s.', 'jetpack' ),
990
					implode( ', ', $labels )
991
				) . $view_post_link_html;
992
			}
993
		}
994
995
		$messages['jetpack-portfolio'][6] = sprintf(
996
			/* translators: %1$s is a comma-separated list of services and accounts. Ex. Facebook (@jetpack), Twitter (@jetpack) */
997
			esc_html__( 'Project published and sharing project on %1$s.', 'jetpack' ),
998
			implode( ', ', $labels )
999
		) . $view_post_link_html;
1000
1001
		return $messages;
1002
	}
1003
1004
	/**
1005
	 * Get the Connections the Post was just Publicized to.
1006
	 *
1007
	 * Only reliable just after the Post was published.
1008
	 *
1009
	 * @param int $post_id
1010
	 * @return string[] Array of Service display name => Connection display name
1011
	 */
1012
	function get_publicizing_services( $post_id ) {
1013
		$services = array();
1014
1015
		foreach ( (array) $this->get_services( 'connected' ) as $service_name => $connections ) {
1016
			// services have multiple connections.
1017
			foreach ( $connections as $connection ) {
1018
				$unique_id = '';
1019 View Code Duplication
				if ( ! empty( $connection->unique_id ) )
1020
					$unique_id = $connection->unique_id;
1021
				else if ( ! empty( $connection['connection_data']['token_id'] ) )
1022
					$unique_id = $connection['connection_data']['token_id'];
1023
1024
				// Did we skip this connection?
1025
				if ( get_post_meta( $post_id, $this->POST_SKIP . $unique_id,  true ) ) {
1026
					continue;
1027
				}
1028
				$services[ $this->get_service_label( $service_name ) ][] = $this->get_display_name( $service_name, $connection );
1029
			}
1030
		}
1031
1032
		return $services;
1033
	}
1034
1035
	/**
1036
	 * Is the post Publicize-able?
1037
	 *
1038
	 * Only valid prior to Publicizing a Post.
1039
	 *
1040
	 * @param WP_Post $post
1041
	 * @return bool
1042
	 */
1043
	function post_is_publicizeable( $post ) {
1044
		if ( ! $this->post_type_is_publicizeable( $post->post_type ) )
1045
			return false;
1046
1047
		// This is more a precaution. To only publicize posts that are published. (Mostly relevant for Jetpack sites)
1048
		if ( 'publish' !== $post->post_status ) {
1049
			return false;
1050
		}
1051
1052
		// If it's not flagged as ready, then abort. @see ::flag_post_for_publicize()
1053
		if ( ! get_post_meta( $post->ID, $this->PENDING, true ) )
1054
			return false;
1055
1056
		return true;
1057
	}
1058
1059
	/**
1060
	 * Is a given post type Publicize-able?
1061
	 *
1062
	 * Not every CPT lends itself to Publicize-ation.  Allow CPTs to register by adding their CPT via
1063
	 * the publicize_post_types array filter.
1064
	 *
1065
	 * @param string $post_type The post type to check.
1066
	 * @return bool True if the post type can be Publicized.
1067
	 */
1068
	function post_type_is_publicizeable( $post_type ) {
1069
		if ( 'post' == $post_type )
1070
			return true;
1071
1072
		return post_type_supports( $post_type, 'publicize' );
1073
	}
1074
1075
	/**
1076
	 * Already-published posts should not be Publicized by default. This filter sets checked to
1077
	 * false if a post has already been published.
1078
	 *
1079
	 * Attached to the `publicize_checkbox_default` filter
1080
	 *
1081
	 * @param bool $checked
1082
	 * @param int $post_id
1083
	 * @param string $service_name 'facebook', 'twitter', etc
1084
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
1085
	 * @return bool
1086
	 */
1087
	function publicize_checkbox_default( $checked, $post_id, $service_name, $connection ) {
1088
		if ( 'publish' == get_post_status( $post_id ) ) {
1089
			return false;
1090
		}
1091
1092
		return $checked;
1093
	}
1094
1095
/*
1096
 * Util
1097
 */
1098
1099
	/**
1100
	 * Converts a Publicize message template string into a sprintf format string
1101
	 *
1102
	 * @param string[] $args
1103
	 *               0 - The Publicize message template: 'Check out my post: %title% @ %url'
1104
	 *             ... - The template tags 'title', 'url', etc.
1105
	 * @return string
1106
	 */
1107
	protected static function build_sprintf( $args ) {
1108
		$search = array();
1109
		$replace = array();
1110
		foreach ( $args as $k => $arg ) {
1111
			if ( 0 == $k ) {
1112
				$string = $arg;
1113
				continue;
1114
			}
1115
			$search[] = "%$arg%";
1116
			$replace[] = "%$k\$s";
1117
		}
1118
		return str_replace( $search, $replace, $string );
0 ignored issues
show
Bug introduced by
The variable $string 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...
1119
	}
1120
}
1121
1122
function publicize_calypso_url() {
1123
	$calypso_sharing_url = 'https://wordpress.com/sharing/';
1124
	if ( class_exists( 'Jetpack' ) && method_exists( 'Jetpack', 'build_raw_urls' ) ) {
1125
		$site_suffix = Jetpack::build_raw_urls( home_url() );
1126
	} elseif ( class_exists( 'WPCOM_Masterbar' ) && method_exists( 'WPCOM_Masterbar', 'get_calypso_site_slug' ) ) {
1127
		$site_suffix = WPCOM_Masterbar::get_calypso_site_slug( get_current_blog_id() );
1128
	}
1129
1130
	if ( $site_suffix ) {
1131
		return $calypso_sharing_url . $site_suffix;
0 ignored issues
show
Bug introduced by
The variable $site_suffix 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...
1132
	} else {
1133
		return $calypso_sharing_url;
1134
	}
1135
}
1136