Completed
Push — iterate/calypsoify ( 2ba5fb...4d78ff )
by George
146:23 queued 138:29
created

Publicize_Base::test_connection()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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