Completed
Push — master-stable ( 123e21...46eadb )
by
unknown
62:16 queued 49:39
created

modules/publicize/publicize.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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 = Publicize_Util::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 = Publicize_Util::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 = Publicize_Util::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
		// Connection test callback
112
		add_action( 'wp_ajax_test_publicize_conns', array( $this, 'test_publicize_conns' ) );
113
	}
114
115
	/**
116
	* Functions to be implemented by the extended class (publicize-wpcom or publicize-jetpack)
117
	*/
118
	abstract function get_connection_id( $connection );
119
	abstract function get_connection_meta( $connection );
120
	abstract function get_services( $filter );
121
	abstract function get_connections( $service, $_blog_id = false, $_user_id = false );
122
	abstract function get_connection( $service, $id, $_blog_id = false, $_user_id = false );
123
	abstract function flag_post_for_publicize( $new_status, $old_status, $post );
124
	abstract function test_connection( $service_name, $connection );
125
126
	/**
127
	* Shared Functions
128
	*/
129
130
	/**
131
	* Returns an external URL to the connection's profile
132
	*/
133
	function get_profile_link( $service_name, $c ) {
134
		$cmeta = $this->get_connection_meta( $c );
135
136
		if ( isset( $cmeta['connection_data']['meta']['link'] ) ) {
137
			if ( 'facebook' == $service_name && 0 === strpos( parse_url( $cmeta['connection_data']['meta']['link'], PHP_URL_PATH ), '/app_scoped_user_id/' ) ) {
138
				// App-scoped Facebook user IDs are not usable profile links
139
				return false;
140
			}
141
142
			return $cmeta['connection_data']['meta']['link'];
143 View Code Duplication
		} elseif ( 'facebook' == $service_name && isset( $cmeta['connection_data']['meta']['facebook_page'] ) ) {
144
			return 'https://facebook.com/' . $cmeta['connection_data']['meta']['facebook_page'];
145
		} elseif ( 'tumblr' == $service_name && isset( $cmeta['connection_data']['meta']['tumblr_base_hostname'] ) ) {
146
			 return 'http://' . $cmeta['connection_data']['meta']['tumblr_base_hostname'];
147
		} elseif ( 'twitter' == $service_name ) {
148
			return 'https://twitter.com/' . substr( $cmeta['external_display'], 1 ); // Has a leading '@'
149 View Code Duplication
		} elseif ( 'google_plus' == $service_name && isset( $cmeta['connection_data']['meta']['google_plus_page'] ) ) {
150
			return 'https://plus.google.com/' . $cmeta['connection_data']['meta']['google_plus_page'];
151
		} elseif ( 'google_plus' == $service_name ) {
152
			return 'https://plus.google.com/' . $cmeta['external_id'];
153
		} else if ( 'linkedin' == $service_name ) {
154
			if ( !isset( $cmeta['connection_data']['meta']['profile_url'] ) ) {
155
				return false;
156
			}
157
158
			$profile_url_query = parse_url( $cmeta['connection_data']['meta']['profile_url'], PHP_URL_QUERY );
159
			wp_parse_str( $profile_url_query, $profile_url_query_args );
160
			if ( isset( $profile_url_query_args['key'] ) ) {
161
				$id = $profile_url_query_args['key'];
162
			} elseif ( isset( $profile_url_query_args['id'] ) ) {
163
				$id = $profile_url_query_args['id'];
164
			} else {
165
				return false;
166
			}
167
168
			return esc_url_raw( add_query_arg( 'id', urlencode( $id ), 'http://www.linkedin.com/profile/view' ) );
169
		} else {
170
			return false; // no fallback. we just won't link it
171
		}
172
	}
173
174
	/**
175
	* Returns a display name for the connection
176
	*/
177
	function get_display_name( $service_name, $c ) {
178
		$cmeta = $this->get_connection_meta( $c );
179
180
		if ( isset( $cmeta['connection_data']['meta']['display_name'] ) ) {
181
			return $cmeta['connection_data']['meta']['display_name'];
182 View Code Duplication
		} elseif ( $service_name == 'tumblr' && isset( $cmeta['connection_data']['meta']['tumblr_base_hostname'] ) ) {
183
			 return $cmeta['connection_data']['meta']['tumblr_base_hostname'];
184
		} elseif ( $service_name == 'twitter' ) {
185
			return $cmeta['external_display'];
186
		} else {
187
			$connection_display = $cmeta['external_display'];
188
			if ( empty( $connection_display ) )
189
				$connection_display = $cmeta['external_name'];
190
			return $connection_display;
191
		}
192
	}
193
194
	public static function get_service_label( $service_name ) {
195
		switch ( $service_name ) {
196
			case 'linkedin':
197
				return 'LinkedIn';
198
				break;
0 ignored issues
show
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...
199
			case 'google_plus':
200
				return  'Google+';
201
				break;
202
			case 'twitter':
203
			case 'facebook':
204
			case 'tumblr':
205
			default:
206
				return ucfirst( $service_name );
207
				break;
208
		}
209
	}
210
211
	function show_options_popup( $service_name, $c ) {
212
		$cmeta = $this->get_connection_meta( $c );
213
214
		// always show if no selection has been made for facebook
215
		if ( 'facebook' == $service_name && empty( $cmeta['connection_data']['meta']['facebook_profile'] ) && empty( $cmeta['connection_data']['meta']['facebook_page'] ) )
216
			return true;
217
218
		// always show if no selection has been made for tumblr
219
		if ( 'tumblr' == $service_name && empty ( $cmeta['connection_data']['meta']['tumblr_base_hostname'] ) )
220
			return true;
221
222
		// if we have the specific connection info..
223
		if ( isset( $_GET['id'] ) ) {
224
			if ( $cmeta['connection_data']['id'] == $_GET['id'] )
225
				return true;
226
		} else {
227
			// otherwise, just show if this is the completed step / first load
228
			if ( !empty( $_GET['action'] ) && 'completed' == $_GET['action'] && !empty( $_GET['service'] ) && $service_name == $_GET['service'] && ! in_array( $_GET['service'], array( 'facebook', 'tumblr' ) ) )
229
				return true;
230
		}
231
232
		return false;
233
	}
234
235
	function user_id() {
236
		global $current_user;
237
		return $current_user->ID;
238
	}
239
240
	function blog_id() {
241
		return get_current_blog_id();
242
	}
243
244
	/**
245
	* Returns true if a user has a connection to a particular service, false otherwise
246
	*/
247
	function is_enabled( $service, $_blog_id = false, $_user_id = false ) {
248
		if ( !$_blog_id )
249
			$_blog_id = $this->blog_id();
250
251
		if ( !$_user_id )
252
			$_user_id = $this->user_id();
253
254
		$connections = $this->get_connections( $service, $_blog_id, $_user_id );
255
		return ( is_array( $connections ) && count( $connections ) > 0 ? true : false );
256
	}
257
258
	/**
259
	* Fires when a post is saved, checks conditions and saves state in postmeta so that it
260
	* can be picked up later by @see ::publicize_post()
261
	*/
262
	function save_meta( $post_id, $post ) {
263
		$cron_user = null;
264
		$submit_post = true;
265
266
		if ( ! $this->post_type_is_publicizeable( $post->post_type ) )
267
			return;
268
269
		// Don't Publicize during certain contexts:
270
271
		// - import
272
		if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING  ) {
273
			$submit_post = false;
274
		}
275
276
		// - on quick edit, autosave, etc but do fire on p2, quickpress, and instapost ajax
277
		if (
278
			defined( 'DOING_AJAX' )
279
		&&
280
			DOING_AJAX
281
		&&
282
			!did_action( 'p2_ajax' )
283
		&&
284
			!did_action( 'wp_ajax_json_quickpress_post' )
285
		&&
286
			!did_action( 'wp_ajax_instapost_publish' )
287
		&&
288
			!did_action( 'wp_ajax_post_reblog' )
289
		) {
290
			$submit_post = false;
291
		}
292
293
		// - bulk edit
294
		if ( isset( $_GET['bulk_edit'] ) ) {
295
			$submit_post = false;
296
		}
297
298
		// - API/XML-RPC Test Posts
299
		if (
300
			(
301
				defined( 'XMLRPC_REQUEST' )
302
			&&
303
				XMLRPC_REQUEST
304
			||
305
				defined( 'APP_REQUEST' )
306
			&&
307
				APP_REQUEST
308
			)
309
		&&
310
			0 === strpos( $post->post_title, 'Temporary Post Used For Theme Detection' )
311
		) {
312
			$submit_post = false;
313
		}
314
315
		// only work with certain statuses (avoids inherits, auto drafts etc)
316
		if ( !in_array( $post->post_status, array( 'publish', 'draft', 'future' ) ) ) {
317
			$submit_post = false;
318
		}
319
320
		// don't publish password protected posts
321
		if ( '' !== $post->post_password ) {
322
			$submit_post = false;
323
		}
324
325
		/**
326
		 * Filter if a post should be skipped during Publicize.
327
		 *
328
		 * @module publicize
329
		 *
330
		 * @since 3.9.0
331
		 *
332
		 * @param bool   $skip    Should the post be skipped? Default false.
333
		 * @param int    $post_id The post ID being considered.
334
		 * @param object $post    The post object being considered.
335
		 */
336
		if ( apply_filters( 'jetpack_skip_all_publicize', false, $post_id, $post ) ) {
337
			$submit_post = false;
338
		}
339
340
		// Did this request happen via wp-admin?
341
		$from_web = 'post' == strtolower( $_SERVER['REQUEST_METHOD'] ) && isset( $_POST[$this->ADMIN_PAGE] );
342
343
		if ( ( $from_web || defined( 'POST_BY_EMAIL' ) ) && isset( $_POST['wpas_title'] ) ) {
344
			if ( empty( $_POST['wpas_title'] ) ) {
345
				delete_post_meta( $post_id, $this->POST_MESS );
346
			} else {
347
				update_post_meta( $post_id, $this->POST_MESS, trim( stripslashes( $_POST['wpas_title'] ) ) );
348
			}
349
		}
350
351
		// change current user to provide context for get_services() if we're running during cron
352
		if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
353
			$cron_user = (int) $GLOBALS['user_ID'];
354
			wp_set_current_user( $post->post_author );
355
		}
356
357
		/**
358
		 * In this phase, we mark connections that we want to SKIP. When Publicize is actually triggered,
359
		 * it will Publicize to everything *except* those marked for skipping.
360
		 */
361
		foreach ( (array) $this->get_services( 'connected' ) as $service_name => $connections ) {
362
			foreach ( $connections as $connection ) {
363
				$connection_data = '';
364 View Code Duplication
				if ( method_exists( $connection, 'get_meta' ) )
365
					$connection_data = $connection->get_meta( 'connection_data' );
366
				elseif ( ! empty( $connection['connection_data'] ) )
367
					$connection_data = $connection['connection_data'];
368
369
				/** This action is documented in modules/publicize/ui.php */
370
				if ( false == apply_filters( 'wpas_submit_post?', $submit_post, $post_id, $service_name, $connection_data ) ) {
371
					delete_post_meta( $post_id, $this->PENDING );
372
					continue;
373
				}
374
375 View Code Duplication
				if ( !empty( $connection->unique_id ) )
376
					$unique_id = $connection->unique_id;
377
				else if ( !empty( $connection['connection_data']['token_id'] ) )
378
					$unique_id = $connection['connection_data']['token_id'];
379
380
				// This was a wp-admin request, so we need to check the state of checkboxes
381
				if ( $from_web ) {
382
					// delete stray service-based post meta
383
					delete_post_meta( $post_id, $this->POST_SKIP . $service_name );
384
385
					// We *unchecked* this stream from the admin page, or it's set to readonly, or it's a new addition
386
					if ( empty( $_POST[$this->ADMIN_PAGE]['submit'][$unique_id] ) ) {
387
						// Also make sure that the service-specific input isn't there.
388
						// If the user connected to a new service 'in-page' then a hidden field with the service
389
						// name is added, so we just assume they wanted to Publicize to that service.
390
						if ( empty( $_POST[$this->ADMIN_PAGE]['submit'][$service_name] ) ) {
391
							// Nothing seems to be checked, so we're going to mark this one to be skipped
392
							update_post_meta( $post_id, $this->POST_SKIP . $unique_id, 1 );
393
							continue;
394
						} else {
395
							// clean up any stray post meta
396
							delete_post_meta( $post_id, $this->POST_SKIP . $unique_id );
397
						}
398
					} else {
399
						// The checkbox for this connection is explicitly checked -- make sure we DON'T skip it
400
						delete_post_meta( $post_id, $this->POST_SKIP . $unique_id );
401
					}
402
				}
403
404
				/**
405
				 * Fires right before the post is processed for Publicize.
406
				 * Users may hook in here and do anything else they need to after meta is written,
407
				 * and before the post is processed for Publicize.
408
				 *
409
				 * @since 2.1.2
410
				 *
411
				 * @param bool $submit_post Should the post be publicized.
412
				 * @param int $post->ID Post ID.
413
				 * @param string $service_name Service name.
414
				 * @param array $connection Array of connection details.
415
				 */
416
				do_action( 'publicize_save_meta', $submit_post, $post_id, $service_name, $connection );
417
			}
418
		}
419
420
		if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
421
			wp_set_current_user( $cron_user );
422
		}
423
424
		// Next up will be ::publicize_post()
425
	}
426
427
	/**
428
	 * Is a given post type Publicize-able?
429
	 *
430
	 * Not every CPT lends itself to Publicize-ation.  Allow CPTs to register by adding their CPT via
431
	 * the publicize_post_types array filter.
432
	 *
433
	 * @param string $post_type The post type to check.
434
	 * $return bool True if the post type can be Publicized.
435
	 */
436
	function post_type_is_publicizeable( $post_type ) {
437
		if ( 'post' == $post_type )
438
			return true;
439
440
		return post_type_supports( $post_type, 'publicize' );
441
	}
442
443
	/**
444
	 * Runs tests on all the connections and returns the results to the caller
445
	 */
446
	function test_publicize_conns() {
447
		$test_results = array();
448
449
		foreach ( (array) $this->get_services( 'connected' ) as $service_name => $connections ) {
450
			foreach ( $connections as $connection ) {
451
452
				$id = $this->get_connection_id( $connection );
453
454
				$connection_test_passed = true;
455
				$connection_test_message = __( 'This connection is working correctly.' , 'jetpack' );
456
				$user_can_refresh = false;
457
				$refresh_text = '';
458
				$refresh_url = '';
459
460
				$connection_test_result = true;
461
				if ( method_exists( $this, 'test_connection' ) ) {
462
					$connection_test_result = $this->test_connection( $service_name, $connection );
463
				}
464
465
				if ( is_wp_error( $connection_test_result ) ) {
466
					$connection_test_passed = false;
467
					$connection_test_message = $connection_test_result->get_error_message();
468
					$error_data = $connection_test_result->get_error_data();
469
470
					$user_can_refresh = $error_data['user_can_refresh'];
471
					$refresh_text = $error_data['refresh_text'];
472
					$refresh_url = $error_data['refresh_url'];
473
				}
474
475
				$test_results[] = array(
476
					'connectionID'          => $id,
477
					'serviceName'           => $service_name,
478
					'connectionTestPassed'  => $connection_test_passed,
479
					'connectionTestMessage' => esc_attr( $connection_test_message ),
480
					'userCanRefresh'        => $user_can_refresh,
481
					'refreshText'           => esc_attr( $refresh_text ),
482
					'refreshURL'            => $refresh_url
483
				);
484
			}
485
		}
486
487
		wp_send_json_success( $test_results );
488
	}
489
}
490
491
function publicize_calypso_url() {
492
	$calypso_sharing_url = 'https://wordpress.com/sharing/';
493
	if ( class_exists( 'Jetpack' ) && method_exists( 'Jetpack', 'build_raw_urls' ) ) {
494
		$site_suffix = Jetpack::build_raw_urls( home_url() );
495
	}
496
497
	if ( $site_suffix ) {
498
		return $calypso_sharing_url . $site_suffix;
0 ignored issues
show
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...
499
	} else {
500
		return $calypso_sharing_url;
501
	}
502
}
503