Completed
Push — add/sync-rest-2 ( dcf3c8...9df295 )
by
unknown
10:28
created

Jetpack_Gravatar_Profile_Widget   C

Complexity

Total Complexity 59

Size/Duplication

Total Lines 388
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 59
c 1
b 0
f 0
lcom 1
cbo 0
dl 0
loc 388
rs 6.1904

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 20 3
D widget() 0 100 9
B display_personal_links() 0 36 4
B display_accounts() 0 40 4
C form() 0 65 11
A admin_script() 0 16 1
B update() 0 21 7
C get_profile() 0 31 7
D get_sanitized_service_name() 0 27 10
A enqueue_scripts() 0 15 3

How to fix   Complexity   

Complex Class

Complex classes like Jetpack_Gravatar_Profile_Widget often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Jetpack_Gravatar_Profile_Widget, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * Register the widget for use in Appearance -> Widgets
5
 */
6
add_action( 'widgets_init', 'jetpack_gravatar_profile_widget_init' );
7
8
function jetpack_gravatar_profile_widget_init() {
9
	register_widget( 'Jetpack_Gravatar_Profile_Widget' );
10
}
11
12
/**
13
 * Display a widgetized version of your Gravatar Profile
14
 * http://blog.gravatar.com/2010/03/26/gravatar-profiles/
15
 */
16
class Jetpack_Gravatar_Profile_Widget extends WP_Widget {
17
18
	function __construct() {
19
		parent::__construct(
20
			'grofile',
21
			/** This filter is documented in modules/widgets/facebook-likebox.php */
22
			apply_filters( 'jetpack_widget_name', __( 'Gravatar Profile', 'jetpack' ) ),
23
			array(
24
				'classname'   => 'widget-grofile grofile',
25
				'description' => __( 'Display a mini version of your Gravatar Profile', 'jetpack' ),
26
				'customize_selective_refresh' => true,
27
			)
28
		);
29
30
		if ( is_admin() ) {
31
			add_action( 'admin_footer-widgets.php', array( $this, 'admin_script' ) );
32
		}
33
34
		if ( is_customize_preview() ) {
35
			add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
36
		}
37
	}
38
39
	function widget( $args, $instance ) {
40
41
		$instance = wp_parse_args( $instance, array(
42
			'title' => '',
43
			'email' => ''
44
		) );
45
46
		/** This filter is documented in core/src/wp-includes/default-widgets.php */
47
		$title = apply_filters( 'widget_title', $instance['title'] );
48
49
		if ( !$instance['email'] ) {
50
			if ( current_user_can( 'edit_theme_options' ) ) {
51
				echo $args['before_widget'];
52
				if ( ! empty( $title ) )
53
					echo $args['before_title'] . $title . $args['after_title'];
54
				echo '<p>' . sprintf( __( 'You need to select what to show in this <a href="%s">Gravatar Profile widget</a>.', 'jetpack' ), admin_url( 'widgets.php' ) ) . '</p>';
55
				echo $args['after_widget'];
56
			}
57
			return;
58
		}
59
60
		echo $args['before_widget'];
61
		if ( ! empty( $title ) )
62
			echo $args['before_title'] . $title . $args['after_title'];
63
64
		$profile = $this->get_profile( $instance['email'] );
65
66
		if( ! empty( $profile ) ) {
67
			$profile = wp_parse_args( $profile, array(
68
				'thumbnailUrl' => '',
69
				'profileUrl'   => '',
70
				'displayName'  => '',
71
				'aboutMe'      => '',
72
				'urls'         => array(),
73
				'accounts'     => array(),
74
			) );
75
			$gravatar_url = add_query_arg( 's', 320, $profile['thumbnailUrl'] ); // the default grav returned by grofiles is super small
76
77
			// Enqueue front end assets.
78
			$this->enqueue_scripts();
79
80
			?>
81
			<img src="<?php echo esc_url( $gravatar_url ); ?>" class="grofile-thumbnail no-grav" alt="<?php echo esc_attr( $profile['displayName'] ); ?>" />
82
			<div class="grofile-meta">
83
				<h4><a href="<?php echo esc_url( $profile['profileUrl'] ); ?>"><?php echo esc_html( $profile['displayName'] ); ?></a></h4>
84
				<p><?php echo wp_kses_post( $profile['aboutMe'] ); ?></p>
85
			</div>
86
87
			<?php
88
89
			if( $instance['show_personal_links'] )
90
				$this->display_personal_links( (array) $profile['urls'] );
91
92
			if( $instance['show_account_links'] )
93
				$this->display_accounts( (array) $profile['accounts'] );
94
95
			?>
96
97
			<p><a href="<?php echo esc_url( $profile['profileUrl'] ); ?>" class="grofile-full-link">
98
				<?php echo esc_html(
99
					/**
100
					 * Filter the Gravatar Profile widget's profile link title.
101
					 *
102
					 * @module widgets
103
					 *
104
					 * @since 2.8.0
105
					 *
106
					 * @param string $str Profile link title.
107
					 */
108
					apply_filters(
109
						'jetpack_gravatar_full_profile_title',
110
						__( 'View Full Profile &rarr;', 'jetpack' )
111
					)
112
				); ?>
113
			</a></p>
114
115
			<?php
116
117
			/**
118
			 * Fires when an item is displayed on the frontend.
119
			 *
120
			 * Can be used to track stats about the number of displays for a specific item
121
			 *
122
			 * @module widgets, shortcodes
123
			 *
124
			 * @since 1.6.0
125
			 *
126
			 * @param string widget Item type (e.g. widget, or embed).
127
			 * @param string grofile Item description (e.g. grofile, goodreads).
128
			 */
129
			do_action( 'jetpack_stats_extra', 'widget', 'grofile' );
130
131
		} else {
132
			if ( current_user_can( 'edit_theme_options' ) ) {
133
				echo '<p>' . esc_html__( 'Error loading profile', 'jetpack' ) . '</p>';
134
			}
135
		}
136
137
		echo $args['after_widget'];
138
	}
139
140
	function display_personal_links( $personal_links = array() ) {
141
		if ( empty( $personal_links ) )
142
			return;
143
		?>
144
145
			<h4><?php echo esc_html(
146
				apply_filters(
147
					/**
148
					 * Filter the Gravatar Profile widget's "Personal Links" section title.
149
					 *
150
					 * @module widgets
151
					 *
152
					 * @since 2.8.0
153
					 *
154
					 * @param string $str "Personal Links" section title.
155
					 */
156
					'jetpack_gravatar_personal_links_title',
157
					__( 'Personal Links', 'jetpack' )
158
					)
159
				); ?></h4>
160
			<ul class="grofile-urls grofile-links">
161
162
			<?php foreach( $personal_links as $personal_link ) : ?>
163
				<li>
164
					<a href="<?php echo esc_url( $personal_link['value'] ); ?>">
165
						<?php
166
							$link_title = ( ! empty( $personal_link['title'] ) ) ? $personal_link['title'] : $personal_link['value'];
167
							echo esc_html( $link_title );
168
						?>
169
					</a>
170
				</li>
171
			<?php endforeach; ?>
172
			</ul>
173
174
		<?php
175
	}
176
177
	function display_accounts( $accounts = array() ) {
178
		if ( empty( $accounts ) )
179
			return;
180
		?>
181
182
		<h4><?php echo esc_html(
183
				/**
184
				 * Filter the Gravatar Profile widget's "Verified Services" section title.
185
				 *
186
				 * @module widgets
187
				 *
188
				 * @since 2.8.0
189
				 *
190
				 * @param string $str "Verified Services" section title.
191
				 */
192
				apply_filters(
193
					'jetpack_gravatar_verified_services_title',
194
					__( 'Verified Services', 'jetpack' )
195
				)
196
			); ?></h4>
197
		<ul class="grofile-urls grofile-accounts">
198
199
		<?php foreach( $accounts as $account ) :
200
			if( $account['verified'] != 'true' )
201
				continue;
202
203
			$sanitized_service_name = $this->get_sanitized_service_name( $account['shortname'] );
204
			?>
205
206
			<li>
207
				<a href="<?php echo esc_url( $account['url'] ); ?>" title="<?php echo sprintf( _x( '%1$s on %2$s', '1: User Name, 2: Service Name (Facebook, Twitter, ...)', 'jetpack' ), esc_html( $account['display'] ), esc_html( $sanitized_service_name ) ); ?>">
208
					<span class="grofile-accounts-logo grofile-accounts-<?php echo esc_attr( $account['shortname'] ); ?> accounts_<?php echo esc_attr( $account['shortname'] ); ?>"></span>
209
				</a>
210
			</li>
211
212
		<?php endforeach; ?>
213
		</ul>
214
215
		<?php
216
	}
217
218
	/**
219
	 * Enqueue CSS and JavaScript.
220
	 *
221
	 * @since 3.10
222
	 */
223
	function enqueue_scripts() {
224
		wp_enqueue_style(
225
			'gravatar-profile-widget',
226
			plugins_url( 'gravatar-profile.css', __FILE__ ),
227
			array(),
228
			'20120711'
229
		);
230
231
		wp_enqueue_style(
232
			'gravatar-card-services',
233
			is_ssl() ? 'https://secure.gravatar.com/css/services.css' : 'http://s.gravatar.com/css/services.css',
234
			array(),
235
			defined( 'GROFILES__CACHE_BUSTER' ) ? GROFILES__CACHE_BUSTER : gmdate( 'YW' )
236
		);
237
	}
238
239
	function form( $instance ) {
240
		$title               = isset( $instance['title'] ) ? $instance['title'] : '';
241
		$email               = isset( $instance['email'] ) ? $instance['email'] : '';
242
		$email_user          = isset( $instance['email_user'] ) ? $instance['email_user'] : get_current_user_id();
243
		$show_personal_links = isset( $instance['show_personal_links'] ) ? (bool) $instance['show_personal_links'] : '';
244
		$show_account_links  = isset( $instance['show_account_links'] ) ? (bool) $instance['show_account_links'] : '';
245
		$profile_url         = 'https://gravatar.com/profile/edit';
246
247
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
248
			$profile_url = admin_url( 'profile.php' );
249
250
			if ( isset( $_REQUEST['calypso'] ) ) {
251
				$profile_url = 'https://wordpress.com/me';
252
			}
253
		}
254
		?>
255
		<p>
256
			<label for="<?php echo $this->get_field_id( 'title' ); ?>">
257
				<?php esc_html_e( 'Title', 'jetpack' ); ?> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
258
			</label>
259
		</p>
260
261
		<p>
262
			<label for="<?php echo $this->get_field_id( 'email_user' ); ?>">
263
				<?php esc_html_e( 'Select a user or pick "custom" and enter a custom email address.', 'jetpack' ); ?>
264
				<br />
265
266
				<?php wp_dropdown_users( array(
267
					'show_option_none' => __( 'Custom', 'jetpack' ),
268
					'selected'         => $email_user,
269
					'name'             => $this->get_field_name( 'email_user' ),
270
					'id'               => $this->get_field_id( 'email_user' ),
271
					'class'            => 'gravatar-profile-user-select',
272
				) );?>
273
			</label>
274
		</p>
275
276
		<p class="gprofile-email-container <?php echo empty( $email_user ) || $email_user == -1 ? '' : 'hidden'; ?>">
277
			<label for="<?php echo $this->get_field_id( 'email' ); ?>"><?php esc_html_e( 'Custom Email Address', 'jetpack' ); ?>
278
				<input class="widefat" id="<?php echo $this->get_field_id('email'); ?>" name="<?php echo $this->get_field_name( 'email' ); ?>" type="text" value="<?php echo esc_attr( $email ); ?>" />
279
			</label>
280
		</p>
281
282
		<p>
283
			<label for="<?php echo $this->get_field_id( 'show_personal_links' ); ?>">
284
				<input type="checkbox" name="<?php echo $this->get_field_name( 'show_personal_links' ); ?>" id="<?php echo $this->get_field_id( 'show_personal_links' ); ?>" <?php checked( $show_personal_links ); ?> />
285
				<?php esc_html_e( 'Show Personal Links', 'jetpack' ); ?>
286
				<br />
287
				<small><?php esc_html_e( 'Links to your websites, blogs, or any other sites that help describe who you are.', 'jetpack' ); ?></small>
288
			</label>
289
		</p>
290
291
		<p>
292
			<label for="<?php echo $this->get_field_id( 'show_account_links' ); ?>">
293
				<input type="checkbox" name="<?php echo $this->get_field_name( 'show_account_links' ); ?>" id="<?php echo $this->get_field_id( 'show_account_links' ); ?>" <?php checked( $show_account_links ); ?> />
294
				<?php esc_html_e( 'Show Account Links', 'jetpack' ); ?>
295
				<br />
296
				<small><?php esc_html_e( 'Links to services that you use across the web.', 'jetpack' ); ?></small>
297
			</label>
298
		</p>
299
300
		<p><a href="<?php echo esc_url( $profile_url ); ?>" target="_blank" title="<?php esc_attr_e( 'Opens in new window', 'jetpack' ); ?>"><?php esc_html_e( 'Edit Your Profile', 'jetpack' )?></a> | <a href="http://gravatar.com" target="_blank" title="<?php esc_attr_e( 'Opens in new window', 'jetpack' ); ?>"><?php esc_html_e( "What's a Gravatar?", 'jetpack' ); ?></a></p>
301
302
		<?php
303
	}
304
305
	function admin_script() {
306
		?>
307
		<script>
308
		jQuery( function( $ ) {
309
			$( '.wrap' ).on( 'change', '.gravatar-profile-user-select', function() {
310
				var $input = $(this).closest('.widget-inside').find('.gprofile-email-container');
311
				if ( '-1' === this.value.toLowerCase() ) {
312
					$input.show();
313
				} else {
314
					$input.hide();
315
				}
316
			});
317
		} );
318
		</script>
319
		<?php
320
	}
321
322
	function update( $new_instance, $old_instance ) {
323
324
		$instance = array();
325
326
		$instance['title']               = isset( $new_instance['title'] ) ? wp_kses( $new_instance['title'], array() ) : '';
327
		$instance['email']               = isset( $new_instance['email'] ) ? wp_kses( $new_instance['email'], array() ) : '';
328
		$instance['email_user']          = isset( $new_instance['email_user'] ) ? intval( $new_instance['email_user'] ) : -1;
329
		$instance['show_personal_links'] = isset( $new_instance['show_personal_links'] ) ? (bool) $new_instance['show_personal_links'] : false;
330
		$instance['show_account_links']  = isset( $new_instance['show_account_links'] ) ? (bool) $new_instance['show_account_links'] : false;
331
332
		if ( $instance['email_user'] > 0 ) {
333
			$user = get_userdata( $instance['email_user'] );
334
			$instance['email'] = $user->user_email;
335
		}
336
337
		$hashed_email = md5( strtolower( trim( $instance['email'] ) ) );
338
		$cache_key = 'grofile-' . $hashed_email;
339
		delete_transient( $cache_key );
340
341
		return $instance;
342
	}
343
344
	private function get_profile( $email ) {
345
		$hashed_email = md5( strtolower( trim( $email ) ) );
346
		$cache_key = 'grofile-' . $hashed_email;
347
348
		if( ! $profile = get_transient( $cache_key ) ) {
349
			$profile_url = esc_url_raw( sprintf( '%s.gravatar.com/%s.json', ( is_ssl() ? 'https://secure' : 'http://www' ), $hashed_email ), array( 'http', 'https' ) );
350
351
			$expire = 300;
352
			$response = wp_remote_get( $profile_url, array( 'User-Agent' => 'WordPress.com Gravatar Profile Widget' ) );
353
			$response_code = wp_remote_retrieve_response_code( $response );
354
			if ( 200 == $response_code ) {
355
				$profile = wp_remote_retrieve_body( $response );
356
				$profile = json_decode( $profile, true );
357
358
				if ( is_array( $profile ) && ! empty( $profile['entry'] ) && is_array( $profile['entry'] ) ) {
359
					$expire = 900; // cache for 15 minutes
360
					$profile = $profile['entry'][0];
361
				} else {
362
					// Something strange happened.  Cache for 5 minutes.
363
					$profile = array();
364
				}
365
366
			} else {
367
				$expire = 900; // cache for 15 minutes
368
				$profile = array();
369
			}
370
371
			set_transient( $cache_key, $profile, $expire );
372
		}
373
		return $profile;
374
	}
375
376
	private function get_sanitized_service_name( $shortname ) {
377
		// Some services have stylized or mixed cap names *cough* WP *cough*
378
		switch( $shortname ) {
379
			case 'friendfeed':
380
				return 'FriendFeed';
381
			case 'linkedin':
382
				return 'LinkedIn';
383
			case 'yahoo':
384
				return 'Yahoo!';
385
			case 'youtube':
386
				return 'YouTube';
387
			case 'wordpress':
388
				return 'WordPress';
389
			case 'tripit':
390
				return 'TripIt';
391
			case 'myspace':
392
				return 'MySpace';
393
			case 'foursquare':
394
				return 'foursquare';
395
			case 'google':
396
				return 'Google+';
397
			default:
398
				// Others don't
399
				$shortname = ucwords( $shortname );
400
		}
401
		return $shortname;
402
	}
403
}
404
405
// END
406