Completed
Push — add/publicize-rest-api-2 ( 2e7c1b...de048e )
by
unknown
06:56
created

Publicize_Base::get_connections()

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
		add_action( 'init', array( $this, 'add_post_type_support' ) );
121
		add_action( 'init', array( $this, 'register_post_meta' ), 20 );
122
123
		// Set up publicize flags right before post is actually published.
124
		add_filter( 'rest_pre_insert_post', array( $this, 'process_publicize_from_rest' ), 10, 2 );
125
	}
126
127
/*
128
 * Services: Facebook, Twitter, etc.
129
 */
130
131
	/**
132
	 * Get services for the given blog and user.
133
	 *
134
	 * Can return all available services or just the ones with an active connection.
135
	 *
136
	 * @param string $filter
137
	 *        'all' (default) - Get all services available for connecting
138
	 *        'connected'     - Get all services currently connected
139
	 * @param false|int $_blog_id The blog ID. Use false (default) for the current blog
140
	 * @param false|int $_user_id The user ID. Use false (default) for the current user
141
	 * @return array
142
	 */
143
	abstract function get_services( $filter = 'all', $_blog_id = false, $_user_id = false );
144
145
	/**
146
	 * Does the given user have a connection to the service on the given blog?
147
	 *
148
	 * @param string $service_name 'facebook', 'twitter', etc.
149
	 * @param false|int $_blog_id The blog ID. Use false (default) for the current blog
150
	 * @param false|int $_user_id The user ID. Use false (default) for the current user
151
	 * @return bool
152
	 */
153
	function is_enabled( $service_name, $_blog_id = false, $_user_id = false ) {
154
		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...
155
			$_blog_id = $this->blog_id();
156
157
		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...
158
			$_user_id = $this->user_id();
159
160
		$connections = $this->get_connections( $service_name, $_blog_id, $_user_id );
161
		return ( is_array( $connections ) && count( $connections ) > 0 ? true : false );
162
	}
163
164
	/**
165
	 * Generates a connection URL.
166
	 *
167
	 * This is the URL, which, when visited by the user, starts the authentication
168
	 * process required to forge a connection.
169
	 *
170
	 * @param string $service_name 'facebook', 'twitter', etc.
171
	 * @return string
172
	 */
173
	abstract function connect_url( $service_name );
174
175
	/**
176
	 * Generates a Connection refresh URL.
177
	 *
178
	 * This is the URL, which, when visited by the user, re-authenticates their
179
	 * connection to the service.
180
	 *
181
	 * @param string $service_name 'facebook', 'twitter', etc.
182
	 * @return string
183
	 */
184
	abstract function refresh_url( $service_name );
185
186
	/**
187
	 * Generates a disconnection URL.
188
	 *
189
	 * This is the URL, which, when visited by the user, breaks their connection
190
	 * with the service.
191
	 *
192
	 * @param string $service_name 'facebook', 'twitter', etc.
193
	 * @param string $connection_id Connection ID
194
	 * @return string
195
	 */
196
	abstract function disconnect_url( $service_name, $connection_id );
197
198
	/**
199
	 * Returns a display name for the Service
200
	 *
201
	 * @param string $service_name 'facebook', 'twitter', etc.
202
	 * @return string
203
	 */
204
	public static function get_service_label( $service_name ) {
205
		switch ( $service_name ) {
206
			case 'linkedin':
207
				return 'LinkedIn';
208
				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...
209
			case 'google_plus':
210
				return  'Google+';
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
			case 'twitter':
213
			case 'facebook':
214
			case 'tumblr':
215
			default:
216
				return ucfirst( $service_name );
217
				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...
218
		}
219
	}
220
221
/*
222
 * Connections: For each Service, there can be multiple connections
223
 * for a given user. For example, one user could be connected to Twitter
224
 * as both @jetpack and as @wordpressdotcom
225
 *
226
 * For historical reasons, Connections are represented as an object
227
 * on WordPress.com and as an array in Jetpack.
228
 */
229
230
	/**
231
	 * Get the active Connections of a Service
232
	 *
233
	 * @param string $service_name 'facebook', 'twitter', etc.
234
	 * @param false|int $_blog_id The blog ID. Use false (default) for the current blog
235
	 * @param false|int $_user_id The user ID. Use false (default) for the current user
236
	 * @return false|object[]|array[] false if no connections exist
237
	 */
238
	abstract function get_connections( $service_name, $_blog_id = false, $_user_id = false );
239
240
	/**
241
	 * Get a single Connection of a Service
242
	 *
243
	 * @param string $service_name 'facebook', 'twitter', etc.
244
	 * @param string $connection_id Connection ID
245
	 * @param false|int $_blog_id The blog ID. Use false (default) for the current blog
246
	 * @param false|int $_user_id The user ID. Use false (default) for the current user
247
	 * @return false|object[]|array[] false if no connections exist
248
	 */
249
	abstract function get_connection( $service_name, $connection_id, $_blog_id = false, $_user_id = false );
250
251
	/**
252
	 * Get the Connection ID.
253
	 *
254
	 * Note that this is different than the Connection's uniqueid.
255
	 *
256
	 * Via a quirk of history, ID is globally unique and unique_id
257
	 * is only unique per site.
258
	 *
259
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
260
	 * @return string
261
	 */
262
	abstract function get_connection_id( $connection );
263
264
	/**
265
	 * Get the Connection unique_id
266
	 *
267
	 * Note that this is different than the Connections ID.
268
	 *
269
	 * Via a quirk of history, ID is globally unique and unique_id
270
	 * is only unique per site.
271
	 *
272
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
273
	 * @return string
274
	 */
275
	abstract function get_connection_unique_id( $connection );
276
277
	/**
278
	 * Get the Connection's Meta data
279
	 *
280
	 * @param object|array Connection
281
	 * @return array Connection Meta
282
	 */
283
	abstract function get_connection_meta( $connection );
284
285
	/**
286
	 * Disconnect a Connection
287
	 *
288
	 * @param string $service_name 'facebook', 'twitter', etc.
289
	 * @param string $connection_id Connection ID
290
	 * @param false|int $_blog_id The blog ID. Use false (default) for the current blog
291
	 * @param false|int $_user_id The user ID. Use false (default) for the current user
292
	 * @param bool $force_delete Whether to skip permissions checks
293
	 * @return false|void False on failure. Void on success.
294
	 */
295
	abstract function disconnect( $service_name, $connection_id, $_blog_id = false, $_user_id = false, $force_delete = false );
296
297
	/**
298
	 * Globalizes a Connection
299
	 *
300
	 * @param string $connection_id Connection ID
301
	 * @return bool Falsey on failure. Truthy on success.
302
	 */
303
	abstract function globalize_connection( $connection_id );
304
305
	/**
306
	 * Unglobalizes a Connection
307
	 *
308
	 * @param string $connection_id Connection ID
309
	 * @return bool Falsey on failure. Truthy on success.
310
	 */
311
	abstract function unglobalize_connection( $connection_id );
312
313
	/**
314
	 * Returns an external URL to the Connection's profile
315
	 *
316
	 * @param string $service_name 'facebook', 'twitter', etc.
317
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
318
	 * @return false|string False on failure. URL on success.
319
	 */
320
	function get_profile_link( $service_name, $connection ) {
321
		$cmeta = $this->get_connection_meta( $connection );
322
323
		if ( isset( $cmeta['connection_data']['meta']['link'] ) ) {
324
			if ( 'facebook' == $service_name && 0 === strpos( parse_url( $cmeta['connection_data']['meta']['link'], PHP_URL_PATH ), '/app_scoped_user_id/' ) ) {
325
				// App-scoped Facebook user IDs are not usable profile links
326
				return false;
327
			}
328
329
			return $cmeta['connection_data']['meta']['link'];
330 View Code Duplication
		} elseif ( 'facebook' == $service_name && isset( $cmeta['connection_data']['meta']['facebook_page'] ) ) {
331
			return 'https://facebook.com/' . $cmeta['connection_data']['meta']['facebook_page'];
332
		} elseif ( 'tumblr' == $service_name && isset( $cmeta['connection_data']['meta']['tumblr_base_hostname'] ) ) {
333
			 return 'http://' . $cmeta['connection_data']['meta']['tumblr_base_hostname'];
334
		} elseif ( 'twitter' == $service_name ) {
335
			return 'https://twitter.com/' . substr( $cmeta['external_display'], 1 ); // Has a leading '@'
336 View Code Duplication
		} elseif ( 'google_plus' == $service_name && isset( $cmeta['connection_data']['meta']['google_plus_page'] ) ) {
337
			return 'https://plus.google.com/' . $cmeta['connection_data']['meta']['google_plus_page'];
338
		} elseif ( 'google_plus' == $service_name ) {
339
			return 'https://plus.google.com/' . $cmeta['external_id'];
340
		} else if ( 'linkedin' == $service_name ) {
341
			if ( !isset( $cmeta['connection_data']['meta']['profile_url'] ) ) {
342
				return false;
343
			}
344
345
			$profile_url_query = parse_url( $cmeta['connection_data']['meta']['profile_url'], PHP_URL_QUERY );
346
			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...
347
			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...
348
				$id = $profile_url_query_args['key'];
349
			} 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...
350
				$id = $profile_url_query_args['id'];
351
			} else {
352
				return false;
353
			}
354
355
			return esc_url_raw( add_query_arg( 'id', urlencode( $id ), 'http://www.linkedin.com/profile/view' ) );
356
		} else {
357
			return false; // no fallback. we just won't link it
358
		}
359
	}
360
361
	/**
362
	 * Returns a display name for the Connection
363
	 *
364
	 * @param string $service_name 'facebook', 'twitter', etc.
365
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
366
	 * @return string
367
	 */
368
	function get_display_name( $service_name, $connection ) {
369
		$cmeta = $this->get_connection_meta( $connection );
370
371
		if ( isset( $cmeta['connection_data']['meta']['display_name'] ) ) {
372
			return $cmeta['connection_data']['meta']['display_name'];
373 View Code Duplication
		} elseif ( $service_name == 'tumblr' && isset( $cmeta['connection_data']['meta']['tumblr_base_hostname'] ) ) {
374
			 return $cmeta['connection_data']['meta']['tumblr_base_hostname'];
375
		} elseif ( $service_name == 'twitter' ) {
376
			return $cmeta['external_display'];
377
		} else {
378
			$connection_display = $cmeta['external_display'];
379
			if ( empty( $connection_display ) )
380
				$connection_display = $cmeta['external_name'];
381
			return $connection_display;
382
		}
383
	}
384
385
	/**
386
	 * Whether the user needs to select additional options after connecting
387
	 *
388
	 * @param string $service_name 'facebook', 'twitter', etc.
389
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
390
	 * @return bool
391
	 */
392
	function show_options_popup( $service_name, $connection ) {
393
		$cmeta = $this->get_connection_meta( $connection );
394
395
		// always show if no selection has been made for facebook
396
		if ( 'facebook' == $service_name && empty( $cmeta['connection_data']['meta']['facebook_profile'] ) && empty( $cmeta['connection_data']['meta']['facebook_page'] ) )
397
			return true;
398
399
		// always show if no selection has been made for tumblr
400
		if ( 'tumblr' == $service_name && empty ( $cmeta['connection_data']['meta']['tumblr_base_hostname'] ) )
401
			return true;
402
403
		// if we have the specific connection info..
404
		if ( isset( $_GET['id'] ) ) {
405
			if ( $cmeta['connection_data']['id'] == $_GET['id'] )
406
				return true;
407
		} else {
408
			// otherwise, just show if this is the completed step / first load
409
			if ( !empty( $_GET['action'] ) && 'completed' == $_GET['action'] && !empty( $_GET['service'] ) && $service_name == $_GET['service'] && ! in_array( $_GET['service'], array( 'facebook', 'tumblr' ) ) )
410
				return true;
411
		}
412
413
		return false;
414
	}
415
416
	/**
417
	 * Whether the Connection is "valid" wrt Facebook's requirements.
418
	 *
419
	 * Must be connected to a Page (not a Profile).
420
	 * (Also returns true if we're in the middle of the connection process)
421
	 *
422
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
423
	 * @return bool
424
	 */
425
	function is_valid_facebook_connection( $connection ) {
426
		if ( $this->is_connecting_connection( $connection ) ) {
427
			return true;
428
		}
429
		$connection_meta = $this->get_connection_meta( $connection );
430
		$connection_data = $connection_meta['connection_data'];
431
		return isset( $connection_data[ 'meta' ][ 'facebook_page' ] );
432
	}
433
434
	/**
435
	 * Whether the Connection currently being connected
436
	 *
437
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
438
	 * @return bool
439
	 */
440
	function is_connecting_connection( $connection ) {
441
		$connection_meta = $this->get_connection_meta( $connection );
442
		$connection_data = $connection_meta['connection_data'];
443
		return isset( $connection_data[ 'meta' ]['options_responses'] );
444
	}
445
446
	/**
447
	 * AJAX Handler to run connection tests on all Connections
448
	 * @return void
449
	 */
450
	function test_publicize_conns() {
451
		wp_send_json_success( $this->get_publicize_conns_test_results() );
452
	}
453
454
	/**
455
	 * Run connection tests on all Connections
456
	 *
457
	 * @return array {
458
	 *     Array of connection test results.
459
	 *
460
	 *     @type string 'connectionID'          Connection identifier string that is unique for each connection
461
	 *     @type string 'serviceName'           Slug of the connection's service (facebook, twitter, ...)
462
	 *     @type bool   'connectionTestPassed'  Whether the connection test was successful
463
	 *     @type string 'connectionTestMessage' Test success or error message
464
	 *     @type bool   'userCanRefresh'        Whether the user can re-authenticate their connection to the service
465
	 *     @type string 'refreshText'           Message instructing user to re-authenticate their connection to the service
466
	 *     @type string 'refreshURL'            URL, which, when visited by the user, re-authenticates their connection to the service.
467
	 *     @type string 'unique_id'             ID string representing connection
468
	 * }
469
	 */
470
	function get_publicize_conns_test_results() {
471
		$test_results = array();
472
473
		foreach ( (array) $this->get_services( 'connected' ) as $service_name => $connections ) {
474
			foreach ( $connections as $connection ) {
475
476
				$id = $this->get_connection_id( $connection );
477
478
				$connection_test_passed = true;
479
				$connection_test_message = __( 'This connection is working correctly.' , 'jetpack' );
480
				$user_can_refresh = false;
481
				$refresh_text = '';
482
				$refresh_url = '';
483
484
				$connection_test_result = true;
485
				if ( method_exists( $this, 'test_connection' ) ) {
486
					$connection_test_result = $this->test_connection( $service_name, $connection );
487
				}
488
489
				if ( is_wp_error( $connection_test_result ) ) {
490
					$connection_test_passed = false;
491
					$connection_test_message = $connection_test_result->get_error_message();
492
					$error_data = $connection_test_result->get_error_data();
493
494
					$user_can_refresh = $error_data['user_can_refresh'];
495
					$refresh_text = $error_data['refresh_text'];
496
					$refresh_url = $error_data['refresh_url'];
497
				}
498
				// Mark facebook profiles as deprecated
499
				if ( 'facebook' === $service_name ) {
500
					if ( ! $this->is_valid_facebook_connection( $connection ) ) {
501
						$connection_test_passed = false;
502
						$user_can_refresh = false;
503
						$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.' );
504
					}
505
				}
506
507
				$unique_id = null;
508 View Code Duplication
				if ( ! empty( $connection->unique_id ) ) {
509
					$unique_id = $connection->unique_id;
510
				} else if ( ! empty( $connection['connection_data']['token_id'] ) ) {
511
					$unique_id = $connection['connection_data']['token_id'];
512
				}
513
514
				$test_results[] = array(
515
					'connectionID'          => $id,
516
					'serviceName'           => $service_name,
517
					'connectionTestPassed'  => $connection_test_passed,
518
					'connectionTestMessage' => esc_attr( $connection_test_message ),
519
					'userCanRefresh'        => $user_can_refresh,
520
					'refreshText'           => esc_attr( $refresh_text ),
521
					'refreshURL'            => $refresh_url,
522
					'unique_id'             => $unique_id,
523
				);
524
			}
525
		}
526
527
		return $test_results;
528
	}
529
530
	/**
531
	 * Run the connection test for the Connection
532
	 *
533
	 * @param string $service_name 'facebook', 'twitter', etc.
534
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
535
	 * @return WP_Error|true WP_Error on failure. True on success
536
	 */
537
	abstract function test_connection( $service_name, $connection );
538
539
	/**
540
	 * Retrieves current list of connections and applies filters.
541
	 *
542
	 * Retrieves current available connections and checks if the connections
543
	 * have already been used to share current post. Finally, the checkbox
544
	 * form UI fields are calculated. This function exposes connection form
545
	 * data directly as array so it can be retrieved for static HTML generation
546
	 * or JSON consumption.
547
	 *
548
	 * @since 6.7.0
549
	 *
550
	 * @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...
551
	 *
552
	 * @return array {
553
	 *     Array of UI setup data for connection list form.
554
	 *
555
	 *     @type string 'unique_id'     ID string representing connection
556
	 *     @type string 'service_name'  Slug of the connection's service (facebook, twitter, ...)
557
	 *     @type string 'service_label' Service Label (Facebook, Twitter, ...)
558
	 *     @type string 'display_name'  Connection's human-readable Username: "@jetpack"
559
	 *     @type bool   'enabled'       Default value for the connection (e.g., for a checkbox).
560
	 *     @type bool   'done'          Has this connection already been publicized to?
561
	 *     @type bool   'toggleable'    Is the user allowed to change the value for the connection?
562
	 *     @type bool   'global'        Is this connection a global one?
563
	 * }
564
	 */
565
	public function get_filtered_connection_data( $selected_post_id = null ) {
566
		$connection_list = array();
567
568
		$post = get_post( $selected_post_id ); // Defaults to current post if $post_id is null.
569
		// Handle case where there is no current post.
570
		if ( ! empty( $post ) ) {
571
			$post_id = $post->ID;
572
		} else {
573
			$post_id = null;
574
		}
575
576
		$services = $this->get_services( 'connected' );
577
		$all_done = $this->post_is_done_sharing( $post_id );
578
579
		// We don't allow Publicizing to the same external id twice, to prevent spam.
580
		$service_id_done = (array) get_post_meta( $post_id, $this->POST_SERVICE_DONE, true );
581
582
		foreach ( $services as $service_name => $connections ) {
583
			foreach ( $connections as $connection ) {
584
				$connection_meta = $this->get_connection_meta( $connection );
585
				$connection_data = $connection_meta['connection_data'];
586
587
				$unique_id = $this->get_connection_unique_id( $connection );
588
589
590
				// Was this connection (OR, old-format service) already Publicized to?
591
				$done = ! empty( $post ) && (
592
					// New flags
593
					1 == get_post_meta( $post->ID, $this->POST_DONE . $unique_id, true )
594
					||
595
					// old flags
596
					1 == get_post_meta( $post->ID, $this->POST_DONE . $service_name, true )
597
				);
598
599
				/**
600
				 * Filter whether a post should be publicized to a given service.
601
				 *
602
				 * @module publicize
603
				 *
604
				 * @since 2.0.0
605
				 *
606
				 * @param bool true Should the post be publicized to a given service? Default to true.
607
				 * @param int $post_id Post ID.
608
				 * @param string $service_name Service name.
609
				 * @param array $connection_data Array of information about all Publicize details for the site.
610
				 */
611
				if ( ! apply_filters( 'wpas_submit_post?', true, $post_id, $service_name, $connection_data ) ) {
612
					continue;
613
				}
614
615
				// Should we be skipping this one?
616
				$skip = (
617
					(
618
						! empty( $post )
619
						&&
620
						in_array( $post->post_status, array( 'publish', 'draft', 'future' ) )
621
						&&
622
						(
623
							// New flags
624
							get_post_meta( $post->ID, $this->POST_SKIP . $unique_id, true )
625
							||
626
							// Old flags
627
							get_post_meta( $post->ID, $this->POST_SKIP . $service_name )
628
						)
629
					)
630
					||
631
					(
632
						is_array( $connection )
633
						&&
634
						isset( $connection_meta['external_id'] ) && ! empty( $service_id_done[ $service_name ][ $connection_meta['external_id'] ] )
635
					)
636
				);
637
638
				// If this one has already been publicized to, don't let it happen again.
639
				$toggleable = ! $done && ! $all_done;
640
641
				// Determine the state of the checkbox (on/off) and allow filtering.
642
				$enabled = $done || ! $skip;
643
				/**
644
				 * Filter the checkbox state of each Publicize connection appearing in the post editor.
645
				 *
646
				 * @module publicize
647
				 *
648
				 * @since 2.0.1
649
				 *
650
				 * @param bool $enabled Should the Publicize checkbox be enabled for a given service.
651
				 * @param int $post_id Post ID.
652
				 * @param string $service_name Service name.
653
				 * @param array $connection Array of connection details.
654
				 */
655
				$enabled = apply_filters( 'publicize_checkbox_default', $enabled, $post_id, $service_name, $connection );
656
657
				/**
658
				 * If this is a global connection and this user doesn't have enough permissions to modify
659
				 * those connections, don't let them change it.
660
				 */
661
				if ( ! $done && ( 0 == $connection_data['user_id'] && ! current_user_can( $this->GLOBAL_CAP ) ) ) {
662
					$toggleable = false;
663
664
					/**
665
					 * Filters the checkboxes for global connections with non-prilvedged users.
666
					 *
667
					 * @module publicize
668
					 *
669
					 * @since 3.7.0
670
					 *
671
					 * @param bool   $enabled Indicates if this connection should be enabled. Default true.
672
					 * @param int    $post_id ID of the current post
673
					 * @param string $service_name Name of the connection (Facebook, Twitter, etc)
674
					 * @param array  $connection Array of data about the connection.
675
					 */
676
					$enabled = apply_filters( 'publicize_checkbox_global_default', $enabled, $post_id, $service_name, $connection );
677
				}
678
679
				// Force the checkbox to be checked if the post was DONE, regardless of what the filter does.
680
				if ( $done ) {
681
					$enabled = true;
682
				}
683
684
				$connection_list[] = array(
685
					'unique_id'     => $unique_id,
686
					'service_name'  => $service_name,
687
					'service_label' => $this->get_service_label( $service_name ),
688
					'display_name'  => $this->get_display_name( $service_name, $connection ),
689
690
					'enabled'      => $enabled,
691
					'done'         => $done,
692
					'toggleable'   => $toggleable,
693
					'global'       => 0 == $connection_data['user_id'],
694
				);
695
			}
696
		}
697
698
		return $connection_list;
699
	}
700
701
	/**
702
	 * Checks if post has already been shared by Publicize in the past.
703
	 *
704
	 * @since 6.7.0
705
	 *
706
	 * @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...
707
	 *
708
	 * @return bool True if post has already been shared by Publicize, false otherwise.
709
	 */
710
	abstract public function post_is_done_sharing( $post_id = null );
711
712
	/**
713
	 * Retrieves full list of available Publicize connection services.
714
	 *
715
	 * Retrieves current available publicize service connections
716
	 * with associated labels and URLs.
717
	 *
718
	 * @since 6.7.0
719
	 *
720
	 * @return array {
721
	 *     Array of UI service connection data for all services
722
	 *
723
	 *     @type string 'name'  Name of service.
724
	 *     @type string 'label' Display label for service.
725
	 *     @type string 'url'   URL for adding connection to service.
726
	 * }
727
	 */
728
	function get_available_service_data() {
729
		$available_services     = $this->get_services( 'all' );
730
		$available_service_data = array();
731
732
		foreach ( $available_services as $service_name => $service ) {
733
			$available_service_data[] = array(
734
				'name'  => $service_name,
735
				'label' => $this->get_service_label( $service_name ),
736
				'url'   => $this->connect_url( $service_name ),
737
			);
738
		}
739
740
		return $available_service_data;
741
	}
742
743
/*
744
 * Site Data
745
 */
746
747
	function user_id() {
748
		return get_current_user_id();
749
	}
750
751
	function blog_id() {
752
		return get_current_blog_id();
753
	}
754
755
/*
756
 * Posts
757
 */
758
759
	/**
760
	 * Checks old and new status to see if the post should be flagged as
761
	 * ready to Publicize.
762
	 *
763
	 * Attached to the `transition_post_status` filter.
764
	 *
765
	 * @param string $new_status
766
	 * @param string $old_status
767
	 * @param WP_Post $post
768
	 * @return void
769
	 */
770
	abstract function flag_post_for_publicize( $new_status, $old_status, $post );
771
772
	/**
773
	 * Ensures the Post internal post-type supports `publicize`
774
	 *
775
	 * This feature support flag is used by the REST API.
776
	 */
777
	function add_post_type_support() {
778
		add_post_type_support( 'post', 'publicize' );
779
	}
780
781
	/**
782
	 * Can the current user access Publicize Data.
783
	 *
784
	 * @param int $post_id. 0 for general access. Post_ID for specific access.
0 ignored issues
show
Documentation introduced by
There is no parameter named $post_id.. Did you maybe mean $post_id?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
785
	 * @return bool
786
	 */
787
	function current_user_can_access_publicize_data( $post_id = 0 ) {
788
		/**
789
		 * Filter what user capability is required to use the publicize form on the edit post page. Useful if publish post capability has been removed from role.
790
		 *
791
		 * @module publicize
792
		 *
793
		 * @since 4.1.0
794
		 *
795
		 * @param string $capability User capability needed to use publicize
796
		 */
797
		$capability = apply_filters( 'jetpack_publicize_capability', 'publish_posts' );
798
799
		if ( 'publish_posts' == $capability && $post_id ) {
800
			return current_user_can( 'publish_post', $post_id );
801
		}
802
803
		return current_user_can( $capability );
804
	}
805
806
	/**
807
	 * Auth callback for the protected ->POST_MESS post_meta
808
	 *
809
	 * @param bool $allowed
810
	 * @param string $meta_key
811
	 * @param int $object_id Post ID
812
	 * @return bool
813
	 */
814
	function message_meta_auth_callback( $allowed, $meta_key, $object_id ) {
815
		return $this->current_user_can_access_publicize_data( $object_id );
816
	}
817
818
	/**
819
	 * Registers the ->POST_MESS post_meta for use in the REST API.
820
	 *
821
	 * Registers for each post type that with `publicize` feature support.
822
	 */
823
	function register_post_meta() {
824
		$args = array(
825
			'type' => 'string',
826
			'description' => __( 'The message to use instead of the title when sharing to Publicize Services', 'jetpack' ),
827
			'single' => true,
828
			'default' => '',
829
			'show_in_rest' => array(
830
				'name' => 'jetpack_publicize_message'
831
			),
832
			'auth_callback' => array( $this, 'message_meta_auth_callback' ),
833
		);
834
835
		foreach ( get_post_types() as $post_type ) {
836
			if ( ! $this->post_type_is_publicizeable( $post_type ) ) {
837
				continue;
838
			}
839
840
			$args['object_subtype'] = $post_type;
841
842
			register_meta( 'post', $this->POST_MESS, $args );
843
		}
844
	}
845
846
	/**
847
	 * Fires when a post is saved, checks conditions and saves state in postmeta so that it
848
	 * can be picked up later by @see ::publicize_post() on WordPress.com codebase.
849
	 *
850
	 * Attached to the `save_post` action.
851
	 *
852
	 * @param int $post_id
853
	 * @param WP_Post $post
854
	 * @return void
855
	 */
856
	function save_meta( $post_id, $post ) {
857
		$cron_user = null;
858
		$submit_post = true;
859
860
		if ( ! $this->post_type_is_publicizeable( $post->post_type ) )
861
			return;
862
863
		// Don't Publicize during certain contexts:
864
865
		// - import
866
		if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING  ) {
867
			$submit_post = false;
868
		}
869
870
		// - on quick edit, autosave, etc but do fire on p2, quickpress, and instapost ajax
871
		if (
872
			defined( 'DOING_AJAX' )
873
		&&
874
			DOING_AJAX
875
		&&
876
			!did_action( 'p2_ajax' )
877
		&&
878
			!did_action( 'wp_ajax_json_quickpress_post' )
879
		&&
880
			!did_action( 'wp_ajax_instapost_publish' )
881
		&&
882
			!did_action( 'wp_ajax_post_reblog' )
883
		&&
884
			!did_action( 'wp_ajax_press-this-save-post' )
885
		) {
886
			$submit_post = false;
887
		}
888
889
		// - bulk edit
890
		if ( isset( $_GET['bulk_edit'] ) ) {
891
			$submit_post = false;
892
		}
893
894
		// - API/XML-RPC Test Posts
895
		if (
896
			(
897
				defined( 'XMLRPC_REQUEST' )
898
			&&
899
				XMLRPC_REQUEST
900
			||
901
				defined( 'APP_REQUEST' )
902
			&&
903
				APP_REQUEST
904
			)
905
		&&
906
			0 === strpos( $post->post_title, 'Temporary Post Used For Theme Detection' )
907
		) {
908
			$submit_post = false;
909
		}
910
911
		// only work with certain statuses (avoids inherits, auto drafts etc)
912
		if ( !in_array( $post->post_status, array( 'publish', 'draft', 'future' ) ) ) {
913
			$submit_post = false;
914
		}
915
916
		// don't publish password protected posts
917
		if ( '' !== $post->post_password ) {
918
			$submit_post = false;
919
		}
920
921
		// Did this request happen via wp-admin?
922
		$from_web = isset( $_SERVER['REQUEST_METHOD'] )
923
			&&
924
			'post' == strtolower( $_SERVER['REQUEST_METHOD'] )
925
			&&
926
			isset( $_POST[$this->ADMIN_PAGE] );
927
928
		if ( ( $from_web || defined( 'POST_BY_EMAIL' ) ) && isset( $_POST['wpas_title'] ) ) {
929 View Code Duplication
			if ( empty( $_POST['wpas_title'] ) ) {
930
				delete_post_meta( $post_id, $this->POST_MESS );
931
			} else {
932
				update_post_meta( $post_id, $this->POST_MESS, trim( stripslashes( $_POST['wpas_title'] ) ) );
933
			}
934
		}
935
936
		// change current user to provide context for get_services() if we're running during cron
937
		if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
938
			$cron_user = (int) $GLOBALS['user_ID'];
939
			wp_set_current_user( $post->post_author );
940
		}
941
942
		/**
943
		 * In this phase, we mark connections that we want to SKIP. When Publicize is actually triggered,
944
		 * it will Publicize to everything *except* those marked for skipping.
945
		 */
946
		foreach ( (array) $this->get_services( 'connected' ) as $service_name => $connections ) {
947
			foreach ( $connections as $connection ) {
948
				$connection_data = '';
949
				if ( method_exists( $connection, 'get_meta' ) )
950
					$connection_data = $connection->get_meta( 'connection_data' );
951
				elseif ( ! empty( $connection['connection_data'] ) )
952
					$connection_data = $connection['connection_data'];
953
954
				/** This action is documented in modules/publicize/ui.php */
955
				if ( false == apply_filters( 'wpas_submit_post?', $submit_post, $post_id, $service_name, $connection_data ) ) {
956
					delete_post_meta( $post_id, $this->PENDING );
957
					continue;
958
				}
959
960 View Code Duplication
				if ( !empty( $connection->unique_id ) )
961
					$unique_id = $connection->unique_id;
962
				else if ( !empty( $connection['connection_data']['token_id'] ) )
963
					$unique_id = $connection['connection_data']['token_id'];
964
965
				// This was a wp-admin request, so we need to check the state of checkboxes
966
				if ( $from_web ) {
967
					// delete stray service-based post meta
968
					delete_post_meta( $post_id, $this->POST_SKIP . $service_name );
969
970
					// We *unchecked* this stream from the admin page, or it's set to readonly, or it's a new addition
971
					if ( empty( $_POST[$this->ADMIN_PAGE]['submit'][$unique_id] ) ) {
972
						// Also make sure that the service-specific input isn't there.
973
						// If the user connected to a new service 'in-page' then a hidden field with the service
974
						// name is added, so we just assume they wanted to Publicize to that service.
975 View Code Duplication
						if ( empty( $_POST[$this->ADMIN_PAGE]['submit'][$service_name] ) ) {
976
							// Nothing seems to be checked, so we're going to mark this one to be skipped
977
							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...
978
							continue;
979
						} else {
980
							// clean up any stray post meta
981
							delete_post_meta( $post_id, $this->POST_SKIP . $unique_id );
982
						}
983
					} else {
984
						// The checkbox for this connection is explicitly checked -- make sure we DON'T skip it
985
						delete_post_meta( $post_id, $this->POST_SKIP . $unique_id );
986
					}
987
				}
988
989
				/**
990
				 * Fires right before the post is processed for Publicize.
991
				 * Users may hook in here and do anything else they need to after meta is written,
992
				 * and before the post is processed for Publicize.
993
				 *
994
				 * @since 2.1.2
995
				 *
996
				 * @param bool $submit_post Should the post be publicized.
997
				 * @param int $post->ID Post ID.
998
				 * @param string $service_name Service name.
999
				 * @param array $connection Array of connection details.
1000
				 */
1001
				do_action( 'publicize_save_meta', $submit_post, $post_id, $service_name, $connection );
1002
			}
1003
		}
1004
1005
		if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
1006
			wp_set_current_user( $cron_user );
1007
		}
1008
1009
		// Next up will be ::publicize_post()
1010
	}
1011
1012
	/**
1013
	 * Alters the "Post Published" message to include information about where the post
1014
	 * was Publicized to.
1015
	 *
1016
	 * Attached to the `post_updated_messages` filter
1017
	 *
1018
	 * @param string[] $messages
1019
	 * @return string[]
1020
	 */
1021
	public function update_published_message( $messages ) {
1022
		global $post_type, $post_type_object, $post;
1023
		if ( ! $this->post_type_is_publicizeable( $post_type ) ) {
1024
			return $messages;
1025
		}
1026
		$view_post_link_html = '';
1027
		$viewable = is_post_type_viewable( $post_type_object );
1028
		if ( $viewable ) {
1029
			$view_text = esc_html__( 'View post' ); // intentionally omitted domain
1030
1031
			if ( 'jetpack-portfolio' == $post_type ) {
1032
				$view_text = esc_html__( 'View project', 'jetpack' );
1033
			}
1034
1035
			$view_post_link_html = sprintf( ' <a href="%1$s">%2$s</a>',
1036
				esc_url( get_permalink( $post ) ),
1037
				$view_text
1038
			);
1039
		}
1040
1041
		$services = $this->get_publicizing_services( $post->ID );
1042
		if ( empty( $services ) ) {
1043
			return $messages;
1044
		}
1045
1046
		$labels = array();
1047
		foreach ( $services as $service_name => $display_names ) {
1048
			$labels[] = sprintf(
1049
				/* translators: Service name is %1$s, and account name is %2$s. */
1050
				esc_html__( '%1$s (%2$s)', 'jetpack' ),
1051
				esc_html( $service_name ),
1052
				esc_html( implode( ', ', $display_names ) )
1053
			);
1054
		}
1055
1056
		$messages['post'][6] = sprintf(
1057
			/* translators: %1$s is a comma-separated list of services and accounts. Ex. Facebook (@jetpack), Twitter (@jetpack) */
1058
			esc_html__( 'Post published and sharing on %1$s.', 'jetpack' ),
1059
			implode( ', ', $labels )
1060
		) . $view_post_link_html;
1061
1062
		if ( $post_type == 'post' && class_exists('Jetpack_Subscriptions' ) ) {
1063
			$subscription = Jetpack_Subscriptions::init();
1064
			if ( $subscription->should_email_post_to_subscribers( $post ) ) {
1065
				$messages['post'][6] = sprintf(
1066
					/* translators: %1$s is a comma-separated list of services and accounts. Ex. Facebook (@jetpack), Twitter (@jetpack) */
1067
					esc_html__( 'Post published, sending emails to subscribers and sharing post on %1$s.', 'jetpack' ),
1068
					implode( ', ', $labels )
1069
				) . $view_post_link_html;
1070
			}
1071
		}
1072
1073
		$messages['jetpack-portfolio'][6] = sprintf(
1074
			/* translators: %1$s is a comma-separated list of services and accounts. Ex. Facebook (@jetpack), Twitter (@jetpack) */
1075
			esc_html__( 'Project published and sharing project on %1$s.', 'jetpack' ),
1076
			implode( ', ', $labels )
1077
		) . $view_post_link_html;
1078
1079
		return $messages;
1080
	}
1081
1082
	/**
1083
	 * Get the Connections the Post was just Publicized to.
1084
	 *
1085
	 * Only reliable just after the Post was published.
1086
	 *
1087
	 * @param int $post_id
1088
	 * @return string[] Array of Service display name => Connection display name
1089
	 */
1090
	function get_publicizing_services( $post_id ) {
1091
		$services = array();
1092
1093
		foreach ( (array) $this->get_services( 'connected' ) as $service_name => $connections ) {
1094
			// services have multiple connections.
1095
			foreach ( $connections as $connection ) {
1096
				$unique_id = '';
1097 View Code Duplication
				if ( ! empty( $connection->unique_id ) )
1098
					$unique_id = $connection->unique_id;
1099
				else if ( ! empty( $connection['connection_data']['token_id'] ) )
1100
					$unique_id = $connection['connection_data']['token_id'];
1101
1102
				// Did we skip this connection?
1103
				if ( get_post_meta( $post_id, $this->POST_SKIP . $unique_id,  true ) ) {
1104
					continue;
1105
				}
1106
				$services[ $this->get_service_label( $service_name ) ][] = $this->get_display_name( $service_name, $connection );
1107
			}
1108
		}
1109
1110
		return $services;
1111
	}
1112
1113
	/**
1114
	 * Is the post Publicize-able?
1115
	 *
1116
	 * Only valid prior to Publicizing a Post.
1117
	 *
1118
	 * @param WP_Post $post
1119
	 * @return bool
1120
	 */
1121
	function post_is_publicizeable( $post ) {
1122
		if ( ! $this->post_type_is_publicizeable( $post->post_type ) )
1123
			return false;
1124
1125
		// This is more a precaution. To only publicize posts that are published. (Mostly relevant for Jetpack sites)
1126
		if ( 'publish' !== $post->post_status ) {
1127
			return false;
1128
		}
1129
1130
		// If it's not flagged as ready, then abort. @see ::flag_post_for_publicize()
1131
		if ( ! get_post_meta( $post->ID, $this->PENDING, true ) )
1132
			return false;
1133
1134
		return true;
1135
	}
1136
1137
	/**
1138
	 * Is a given post type Publicize-able?
1139
	 *
1140
	 * Not every CPT lends itself to Publicize-ation.  Allow CPTs to register by adding their CPT via
1141
	 * the publicize_post_types array filter.
1142
	 *
1143
	 * @param string $post_type The post type to check.
1144
	 * @return bool True if the post type can be Publicized.
1145
	 */
1146
	function post_type_is_publicizeable( $post_type ) {
1147
		if ( 'post' == $post_type )
1148
			return true;
1149
1150
		return post_type_supports( $post_type, 'publicize' );
1151
	}
1152
1153
	/**
1154
	 * Already-published posts should not be Publicized by default. This filter sets checked to
1155
	 * false if a post has already been published.
1156
	 *
1157
	 * Attached to the `publicize_checkbox_default` filter
1158
	 *
1159
	 * @param bool $checked
1160
	 * @param int $post_id
1161
	 * @param string $service_name 'facebook', 'twitter', etc
1162
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
1163
	 * @return bool
1164
	 */
1165
	function publicize_checkbox_default( $checked, $post_id, $service_name, $connection ) {
1166
		if ( 'publish' == get_post_status( $post_id ) ) {
1167
			return false;
1168
		}
1169
1170
		return $checked;
1171
	}
1172
1173
	/**
1174
	 * Set up Publicize meta fields for publishing post.
1175
	 *
1176
	 * Process 'publicize' REST field to setup Publicize for publishing
1177
	 * post. Sets post meta keys to enable/disable each connection for
1178
	 * the post and sets publicize title meta key if a title message
1179
	 * is provided.
1180
	 *
1181
	 * @since 6.7.0
1182
	 *
1183
	 * @param stdClass        $new_post_obj Updated post object about to be inserted view REST endpoint.
1184
	 * @param WP_REST_Request $request      Request object, possibly containing 'publicize' field {@see add_publicize_rest_fields()}.
1185
	 *
1186
	 * @return WP_Post Returns the original $new_post value unchanged.
1187
	 */
1188
	public function process_publicize_from_rest( $new_post_obj, $request ) {
1189
		if ( property_exists( $new_post_obj, 'ID' ) ) {
1190
			$post = get_post( $new_post_obj->ID );
1191
		} else {
1192
			return $new_post_obj;
1193
		}
1194
1195
		// If 'publicize' field has been set from editor and post is about to be published.
1196
		if ( isset( $request['publicize'] )
1197
				&& ( property_exists( $new_post_obj, 'post_status' ) && ( 'publish' === $new_post_obj->post_status ) )
1198
				&& ( 'publish' !== $post->post_status ) ) {
1199
1200
			$publicize_field = $request['publicize'];
1201
1202 View Code Duplication
			if ( empty( $publicize_field['title'] ) ) {
1203
				delete_post_meta( $post->ID, $this->POST_MESS );
1204
			} else {
1205
				update_post_meta( $post->ID, $this->POST_MESS, trim( stripslashes( $publicize_field['title'] ) ) );
1206
			}
1207
			if ( isset( $publicize_field['connections'] ) ) {
1208
				foreach ( (array) $this->get_services( 'connected' ) as $service_name => $connections ) {
1209
					foreach ( $connections as $connection ) {
1210 View Code Duplication
						if ( ! empty( $connection->unique_id ) ) {
1211
							$unique_id = $connection->unique_id;
1212
						} elseif ( ! empty( $connection['connection_data']['token_id'] ) ) {
1213
							$unique_id = $connection['connection_data']['token_id'];
1214
						}
1215
1216 View Code Duplication
						if ( $this->connection_should_share( $publicize_field['connections'], $unique_id ) ) {
1217
							// Delete skip flag meta key.
1218
							delete_post_meta( $post->ID, $this->POST_SKIP . $unique_id );
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...
1219
						} else {
1220
							// Flag connection to be skipped for this post.
1221
							update_post_meta( $post->ID, $this->POST_SKIP . $unique_id, 1 );
1222
						}
1223
					}
1224
				}
1225
			}
1226
		}
1227
		// Just pass post object through.
1228
		return $new_post_obj;
1229
	}
1230
1231
	/**
1232
	 * Checks if a connection should be shared to.
1233
	 *
1234
	 * Checks $connection_id against $connections_array to see if the connection associated
1235
	 * with $connection_id should be shared to. Will return true if $connection_id is in the
1236
	 * array and 'should_share' property is set to true, and will default to false otherwise.
1237
	 *
1238
	 * @since 6.7.0
1239
	 *
1240
	 * @param array  $connections_array 'connections' from 'publicize' REST field {@see add_publicize_rest_fields()}.
1241
	 * @param string $connection_id     Connection identifier string that is unique for each connection.
1242
	 * @return boolean True if connection should be shared to, false otherwise.
1243
	 */
1244
	private function connection_should_share( $connections_array, $connection_id ) {
1245
		foreach ( $connections_array as $connection ) {
1246
			if ( isset( $connection['unique_id'] )
1247
				&& ( $connection['unique_id'] === $connection_id )
1248
				&& $connection['should_share'] ) {
1249
				return true;
1250
			}
1251
		}
1252
		return false;
1253
	}
1254
1255
/*
1256
 * Util
1257
 */
1258
1259
	/**
1260
	 * Converts a Publicize message template string into a sprintf format string
1261
	 *
1262
	 * @param string[] $args
1263
	 *               0 - The Publicize message template: 'Check out my post: %title% @ %url'
1264
	 *             ... - The template tags 'title', 'url', etc.
1265
	 * @return string
1266
	 */
1267
	protected static function build_sprintf( $args ) {
1268
		$search = array();
1269
		$replace = array();
1270
		foreach ( $args as $k => $arg ) {
1271
			if ( 0 == $k ) {
1272
				$string = $arg;
1273
				continue;
1274
			}
1275
			$search[] = "%$arg%";
1276
			$replace[] = "%$k\$s";
1277
		}
1278
		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...
1279
	}
1280
}
1281
1282
function publicize_calypso_url() {
1283
	$calypso_sharing_url = 'https://wordpress.com/sharing/';
1284
	if ( class_exists( 'Jetpack' ) && method_exists( 'Jetpack', 'build_raw_urls' ) ) {
1285
		$site_suffix = Jetpack::build_raw_urls( home_url() );
1286
	} elseif ( class_exists( 'WPCOM_Masterbar' ) && method_exists( 'WPCOM_Masterbar', 'get_calypso_site_slug' ) ) {
1287
		$site_suffix = WPCOM_Masterbar::get_calypso_site_slug( get_current_blog_id() );
1288
	}
1289
1290
	if ( $site_suffix ) {
1291
		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...
1292
	} else {
1293
		return $calypso_sharing_url;
1294
	}
1295
}
1296