Completed
Push — try/google-maps-api-key ( 26b378...70e570 )
by
unknown
07:47
created

Publicize_Base::globalize_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
 * Site Data
515
 */
516
517
	function user_id() {
518
		return get_current_user_id();
519
	}
520
521
	function blog_id() {
522
		return get_current_blog_id();
523
	}
524
525
/*
526
 * Posts
527
 */
528
529
	/**
530
	 * Checks old and new status to see if the post should be flagged as
531
	 * ready to Publicize.
532
	 *
533
	 * Attached to the `transition_post_status` filter.
534
	 *
535
	 * @param string $new_status
536
	 * @param string $old_status
537
	 * @param WP_Post $post
538
	 * @return void
539
	 */
540
	abstract function flag_post_for_publicize( $new_status, $old_status, $post );
541
542
	/**
543
	 * Fires when a post is saved, checks conditions and saves state in postmeta so that it
544
	 * can be picked up later by @see ::publicize_post() on WordPress.com codebase.
545
	 *
546
	 * Attached to the `save_post` action.
547
	 *
548
	 * @param int $post_id
549
	 * @param WP_Post $post
550
	 * @return void
551
	 */
552
	function save_meta( $post_id, $post ) {
553
		$cron_user = null;
554
		$submit_post = true;
555
556
		if ( ! $this->post_type_is_publicizeable( $post->post_type ) )
557
			return;
558
559
		// Don't Publicize during certain contexts:
560
561
		// - import
562
		if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING  ) {
563
			$submit_post = false;
564
		}
565
566
		// - on quick edit, autosave, etc but do fire on p2, quickpress, and instapost ajax
567
		if (
568
			defined( 'DOING_AJAX' )
569
		&&
570
			DOING_AJAX
571
		&&
572
			!did_action( 'p2_ajax' )
573
		&&
574
			!did_action( 'wp_ajax_json_quickpress_post' )
575
		&&
576
			!did_action( 'wp_ajax_instapost_publish' )
577
		&&
578
			!did_action( 'wp_ajax_post_reblog' )
579
		&&
580
			!did_action( 'wp_ajax_press-this-save-post' )
581
		) {
582
			$submit_post = false;
583
		}
584
585
		// - bulk edit
586
		if ( isset( $_GET['bulk_edit'] ) ) {
587
			$submit_post = false;
588
		}
589
590
		// - API/XML-RPC Test Posts
591
		if (
592
			(
593
				defined( 'XMLRPC_REQUEST' )
594
			&&
595
				XMLRPC_REQUEST
596
			||
597
				defined( 'APP_REQUEST' )
598
			&&
599
				APP_REQUEST
600
			)
601
		&&
602
			0 === strpos( $post->post_title, 'Temporary Post Used For Theme Detection' )
603
		) {
604
			$submit_post = false;
605
		}
606
607
		// only work with certain statuses (avoids inherits, auto drafts etc)
608
		if ( !in_array( $post->post_status, array( 'publish', 'draft', 'future' ) ) ) {
609
			$submit_post = false;
610
		}
611
612
		// don't publish password protected posts
613
		if ( '' !== $post->post_password ) {
614
			$submit_post = false;
615
		}
616
617
		// Did this request happen via wp-admin?
618
		$from_web = isset( $_SERVER['REQUEST_METHOD'] )
619
			&&
620
			'post' == strtolower( $_SERVER['REQUEST_METHOD'] )
621
			&&
622
			isset( $_POST[$this->ADMIN_PAGE] );
623
624
		if ( ( $from_web || defined( 'POST_BY_EMAIL' ) ) && isset( $_POST['wpas_title'] ) ) {
625
			if ( empty( $_POST['wpas_title'] ) ) {
626
				delete_post_meta( $post_id, $this->POST_MESS );
627
			} else {
628
				update_post_meta( $post_id, $this->POST_MESS, trim( stripslashes( $_POST['wpas_title'] ) ) );
629
			}
630
		}
631
632
		// change current user to provide context for get_services() if we're running during cron
633
		if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
634
			$cron_user = (int) $GLOBALS['user_ID'];
635
			wp_set_current_user( $post->post_author );
636
		}
637
638
		/**
639
		 * In this phase, we mark connections that we want to SKIP. When Publicize is actually triggered,
640
		 * it will Publicize to everything *except* those marked for skipping.
641
		 */
642
		foreach ( (array) $this->get_services( 'connected' ) as $service_name => $connections ) {
643
			foreach ( $connections as $connection ) {
644
				$connection_data = '';
645
				if ( method_exists( $connection, 'get_meta' ) )
646
					$connection_data = $connection->get_meta( 'connection_data' );
647
				elseif ( ! empty( $connection['connection_data'] ) )
648
					$connection_data = $connection['connection_data'];
649
650
				/** This action is documented in modules/publicize/ui.php */
651
				if ( false == apply_filters( 'wpas_submit_post?', $submit_post, $post_id, $service_name, $connection_data ) ) {
652
					delete_post_meta( $post_id, $this->PENDING );
653
					continue;
654
				}
655
656 View Code Duplication
				if ( !empty( $connection->unique_id ) )
657
					$unique_id = $connection->unique_id;
658
				else if ( !empty( $connection['connection_data']['token_id'] ) )
659
					$unique_id = $connection['connection_data']['token_id'];
660
661
				// This was a wp-admin request, so we need to check the state of checkboxes
662
				if ( $from_web ) {
663
					// delete stray service-based post meta
664
					delete_post_meta( $post_id, $this->POST_SKIP . $service_name );
665
666
					// We *unchecked* this stream from the admin page, or it's set to readonly, or it's a new addition
667
					if ( empty( $_POST[$this->ADMIN_PAGE]['submit'][$unique_id] ) ) {
668
						// Also make sure that the service-specific input isn't there.
669
						// If the user connected to a new service 'in-page' then a hidden field with the service
670
						// name is added, so we just assume they wanted to Publicize to that service.
671
						if ( empty( $_POST[$this->ADMIN_PAGE]['submit'][$service_name] ) ) {
672
							// Nothing seems to be checked, so we're going to mark this one to be skipped
673
							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...
674
							continue;
675
						} else {
676
							// clean up any stray post meta
677
							delete_post_meta( $post_id, $this->POST_SKIP . $unique_id );
678
						}
679
					} else {
680
						// The checkbox for this connection is explicitly checked -- make sure we DON'T skip it
681
						delete_post_meta( $post_id, $this->POST_SKIP . $unique_id );
682
					}
683
				}
684
685
				/**
686
				 * Fires right before the post is processed for Publicize.
687
				 * Users may hook in here and do anything else they need to after meta is written,
688
				 * and before the post is processed for Publicize.
689
				 *
690
				 * @since 2.1.2
691
				 *
692
				 * @param bool $submit_post Should the post be publicized.
693
				 * @param int $post->ID Post ID.
694
				 * @param string $service_name Service name.
695
				 * @param array $connection Array of connection details.
696
				 */
697
				do_action( 'publicize_save_meta', $submit_post, $post_id, $service_name, $connection );
698
			}
699
		}
700
701
		if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
702
			wp_set_current_user( $cron_user );
703
		}
704
705
		// Next up will be ::publicize_post()
706
	}
707
708
	/**
709
	 * Alters the "Post Published" message to include information about where the post
710
	 * was Publicized to.
711
	 *
712
	 * Attached to the `post_updated_messages` filter
713
	 *
714
	 * @param string[] $messages
715
	 * @return string[]
716
	 */
717
	public function update_published_message( $messages ) {
718
		global $post_type, $post_type_object, $post;
719
		if ( ! $this->post_type_is_publicizeable( $post_type ) ) {
720
			return $messages;
721
		}
722
		$view_post_link_html = '';
723
		$viewable = is_post_type_viewable( $post_type_object );
724
		if ( $viewable ) {
725
			$view_text = esc_html__( 'View post' ); // intentionally omitted domain
726
727
			if ( 'jetpack-portfolio' == $post_type ) {
728
				$view_text = esc_html__( 'View project', 'jetpack' );
729
			}
730
731
			$view_post_link_html = sprintf( ' <a href="%1$s">%2$s</a>',
732
				esc_url( get_permalink( $post ) ),
733
				$view_text
734
			);
735
		}
736
737
		$services = $this->get_publicizing_services( $post->ID );
738
		if ( empty( $services ) ) {
739
			return $messages;
740
		}
741
742
		$labels = array();
743
		foreach ( $services as $service_name => $display_names ) {
744
			$labels[] = sprintf(
745
				/* translators: Service name is %1$s, and account name is %2$s. */
746
				esc_html__( '%1$s (%2$s)', 'jetpack' ),
747
				esc_html( $service_name ),
748
				esc_html( implode( ', ', $display_names ) )
749
			);
750
		}
751
752
		$messages['post'][6] = sprintf(
753
			/* translators: %1$s is a comma-separated list of services and accounts. Ex. Facebook (@jetpack), Twitter (@jetpack) */
754
			esc_html__( 'Post published and sharing on %1$s.', 'jetpack' ),
755
			implode( ', ', $labels )
756
		) . $view_post_link_html;
757
758
		if ( $post_type == 'post' && class_exists('Jetpack_Subscriptions' ) ) {
759
			$subscription = Jetpack_Subscriptions::init();
760
			if ( $subscription->should_email_post_to_subscribers( $post ) ) {
761
				$messages['post'][6] = sprintf(
762
					/* translators: %1$s is a comma-separated list of services and accounts. Ex. Facebook (@jetpack), Twitter (@jetpack) */
763
					esc_html__( 'Post published, sending emails to subscribers and sharing post on %1$s.', 'jetpack' ),
764
					implode( ', ', $labels )
765
				) . $view_post_link_html;
766
			}
767
		}
768
769
		$messages['jetpack-portfolio'][6] = sprintf(
770
			/* translators: %1$s is a comma-separated list of services and accounts. Ex. Facebook (@jetpack), Twitter (@jetpack) */
771
			esc_html__( 'Project published and sharing project on %1$s.', 'jetpack' ),
772
			implode( ', ', $labels )
773
		) . $view_post_link_html;
774
775
		return $messages;
776
	}
777
778
	/**
779
	 * Get the Connections the Post was just Publicized to.
780
	 *
781
	 * Only reliable just after the Post was published.
782
	 *
783
	 * @param int $post_id
784
	 * @return string[] Array of Service display name => Connection display name
785
	 */
786
	function get_publicizing_services( $post_id ) {
787
		$services = array();
788
789
		foreach ( (array) $this->get_services( 'connected' ) as $service_name => $connections ) {
790
			// services have multiple connections.
791
			foreach ( $connections as $connection ) {
792
				$unique_id = '';
793 View Code Duplication
				if ( ! empty( $connection->unique_id ) )
794
					$unique_id = $connection->unique_id;
795
				else if ( ! empty( $connection['connection_data']['token_id'] ) )
796
					$unique_id = $connection['connection_data']['token_id'];
797
798
				// Did we skip this connection?
799
				if ( get_post_meta( $post_id, $this->POST_SKIP . $unique_id,  true ) ) {
800
					continue;
801
				}
802
				$services[ $this->get_service_label( $service_name ) ][] = $this->get_display_name( $service_name, $connection );
803
			}
804
		}
805
806
		return $services;
807
	}
808
809
	/**
810
	 * Is the post Publicize-able?
811
	 *
812
	 * Only valid prior to Publicizing a Post.
813
	 *
814
	 * @param WP_Post $post
815
	 * @return bool
816
	 */
817
	function post_is_publicizeable( $post ) {
818
		if ( ! $this->post_type_is_publicizeable( $post->post_type ) )
819
			return false;
820
821
		// This is more a precaution. To only publicize posts that are published. (Mostly relevant for Jetpack sites)
822
		if ( 'publish' !== $post->post_status ) {
823
			return false;
824
		}
825
826
		// If it's not flagged as ready, then abort. @see ::flag_post_for_publicize()
827
		if ( ! get_post_meta( $post->ID, $this->PENDING, true ) )
828
			return false;
829
830
		return true;
831
	}
832
833
	/**
834
	 * Is a given post type Publicize-able?
835
	 *
836
	 * Not every CPT lends itself to Publicize-ation.  Allow CPTs to register by adding their CPT via
837
	 * the publicize_post_types array filter.
838
	 *
839
	 * @param string $post_type The post type to check.
840
	 * @return bool True if the post type can be Publicized.
841
	 */
842
	function post_type_is_publicizeable( $post_type ) {
843
		if ( 'post' == $post_type )
844
			return true;
845
846
		return post_type_supports( $post_type, 'publicize' );
847
	}
848
849
	/**
850
	 * Already-published posts should not be Publicized by default. This filter sets checked to
851
	 * false if a post has already been published.
852
	 *
853
	 * Attached to the `publicize_checkbox_default` filter
854
	 *
855
	 * @param bool $checked
856
	 * @param int $post_id
857
	 * @param string $service_name 'facebook', 'twitter', etc
858
	 * @param object|array The Connection object (WordPress.com) or array (Jetpack)
859
	 * @return bool
860
	 */
861
	function publicize_checkbox_default( $checked, $post_id, $service_name, $connection ) {
862
		if ( 'publish' == get_post_status( $post_id ) ) {
863
			return false;
864
		}
865
866
		return $checked;
867
	}
868
869
/*
870
 * Util
871
 */
872
873
	/**
874
	 * Converts a Publicize message template string into a sprintf format string
875
	 *
876
	 * @param string[] $args
877
	 *               0 - The Publicize message template: 'Check out my post: %title% @ %url'
878
	 *             ... - The template tags 'title', 'url', etc.
879
	 * @return string
880
	 */
881
	protected static function build_sprintf( $args ) {
882
		$search = array();
883
		$replace = array();
884
		foreach ( $args as $k => $arg ) {
885
			if ( 0 == $k ) {
886
				$string = $arg;
887
				continue;
888
			}
889
			$search[] = "%$arg%";
890
			$replace[] = "%$k\$s";
891
		}
892
		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...
893
	}
894
}
895
896
function publicize_calypso_url() {
897
	$calypso_sharing_url = 'https://wordpress.com/sharing/';
898
	if ( class_exists( 'Jetpack' ) && method_exists( 'Jetpack', 'build_raw_urls' ) ) {
899
		$site_suffix = Jetpack::build_raw_urls( home_url() );
900
	} elseif ( class_exists( 'WPCOM_Masterbar' ) && method_exists( 'WPCOM_Masterbar', 'get_calypso_site_slug' ) ) {
901
		$site_suffix = WPCOM_Masterbar::get_calypso_site_slug( get_current_blog_id() );
902
	}
903
904
	if ( $site_suffix ) {
905
		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...
906
	} else {
907
		return $calypso_sharing_url;
908
	}
909
}
910