Completed
Push — add/milestone-widget ( e94a04...310a71 )
by
unknown
66:23 queued 58:41
created

Jetpack_Milestone_Widget   A

Complexity

Total Complexity 33

Size/Duplication

Total Lines 345
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 345
rs 9.3999
c 0
b 0
f 0
wmc 33
lcom 2
cbo 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
B Milestone_Widget::__construct() 0 42 3
A Milestone_Widget::enqueue_admin() 0 4 2
A Milestone_Widget::enqueue_template() 0 3 1
A Milestone_Widget::styles_template() 0 53 1
A Milestone_Widget::sanitize_color_hex() 0 14 4
A Milestone_Widget::localize_script() 0 8 2
C Milestone_Widget::widget() 0 67 13
A Milestone_Widget::update() 0 3 1
A Milestone_Widget::sanitize_range() 0 8 3
B Milestone_Widget::sanitize_instance() 0 34 1
A Milestone_Widget::form() 0 48 2
1
<?php
2
/*
3
Plugin Name: Milestone
4
Description: Countdown to a specific date.
5
Version: 1.0
6
Author: Automattic Inc.
7
Author URI: http://automattic.com/
8
License: GPLv2 or later
9
*/
10
11
class Jetpack_Milestone {
12
	public static function init() {
13
		add_action( 'widgets_init', array( __class__, 'register_widget' ) );
14
	}
15
	public static function register_widget() {
16
		register_widget( 'Milestone_Widget' );
17
	}
18
}
19
20
Jetpack_Milestone::init();
21
22
class Milestone_Widget extends WP_Widget {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
23
	private static $dir       = null;
24
	private static $url       = null;
25
	private static $labels    = null;
26
	private static $defaults  = null;
0 ignored issues
show
Unused Code introduced by
The property $defaults is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
27
	private static $config_js = null;
28
29
	function __construct() {
30
		$widget = array(
31
			'classname'   => 'milestone-widget',
32
			'description' => __( 'Display a countdown to a certain date.' )
33
		);
34
35
		$control = array(
36
			'width' => 251, // Chrome needs a little extra room for the date fields.
37
		);
38
39
		parent::__construct(
40
			'Milestone_Widget',
41
			/** This filter is documented in modules/widgets/facebook-likebox.php */
42
			apply_filters( 'jetpack_widget_name', __( 'Milestone', 'jetpack' ) ),
43
			$widget,
44
			$control
45
		);
46
47
		self::$dir = trailingslashit( __DIR__ );
48
		self::$url = plugin_dir_url( __FILE__ );
49
		self::$labels = array(
50
			'year'    => __( 'year' ),
51
			'years'   => __( 'years' ),
52
			'month'   => __( 'month' ),
53
			'months'  => __( 'months' ),
54
			'day'     => __( 'day' ),
55
			'days'    => __( 'days' ),
56
			'hour'    => __( 'hour' ),
57
			'hours'   => __( 'hours' ),
58
			'minute'  => __( 'minute' ),
59
			'minutes' => __( 'minutes' ),
60
			'second'  => __( 'second' ),
61
			'seconds' => __( 'seconds' ),
62
		);
63
64
		add_action( 'wp_enqueue_scripts', array( __class__, 'enqueue_template' ) );
65
		add_action( 'admin_enqueue_scripts', array( __class__, 'enqueue_admin' ) );
66
		add_action( 'wp_footer', array( __class__, 'localize_script' ) );
67
68
		if ( is_active_widget( false, false, $this->id_base, true ) || is_active_widget( false, false, 'monster', true ) )
69
			add_action( 'wp_head', array( __class__, 'styles_template' ) );
70
	}
71
72
	public static function enqueue_admin( $hook_suffix ) {
73
		if ( 'widgets.php' == $hook_suffix )
74
			wp_enqueue_style( 'milestone-admin', self::$url . 'style-admin.css', array(), '20111212' );
75
	}
76
77
	public static function enqueue_template() {
78
		wp_enqueue_script( 'milestone', self::$url . 'milestone.js', array( 'jquery' ), '20160520', true );
79
	}
80
81
	public static function styles_template() {
82
		global $themecolors;
83
		$colors = wp_parse_args( $themecolors, array(
84
			'bg'     => 'ffffff',
85
			'border' => 'cccccc',
86
			'text'   => '333333',
87
		) );
88
?>
89
<style>
90
.milestone-widget {
91
	margin-bottom: 1em;
92
}
93
.milestone-content {
94
	line-height: 2;
95
	margin-top: 5px;
96
	max-width: 17em;
97
	padding: 0;
98
	text-align: center;
99
}
100
.milestone-header {
101
	background-color: <?php echo self::sanitize_color_hex( $colors['text'] ); ?>;
102
	color: <?php echo self::sanitize_color_hex( $colors['bg'] ); ?>;
103
	line-height: 1.3;
104
	margin: 0;
105
	padding: .8em;
106
}
107
.milestone-header .event,
108
.milestone-header .date {
109
	display: block;
110
}
111
.milestone-header .event {
112
	font-size: 120%;
113
}
114
.milestone-countdown .difference {
115
	display: block;
116
	font-size: 500%;
117
	font-weight: bold;
118
	line-height: 1.2;
119
}
120
.milestone-countdown,
121
.milestone-message {
122
	background-color: <?php echo self::sanitize_color_hex( $colors['bg'] ); ?>;
123
	border: 1px solid <?php echo self::sanitize_color_hex( $colors['border'] ); ?>;
124
	border-top: 0;
125
	color: <?php echo self::sanitize_color_hex( $colors['text'] ); ?>;
126
	padding-bottom: 1em;
127
}
128
.milestone-message {
129
	padding-top: 1em
130
}
131
</style>
132
<?php
133
	}
134
135
	/**
136
	 * Ensure that a string representing a color in hexadecimal
137
	 * notation is safe for use in css and database saves.
138
	 *
139
	 * @param string Color in hexadecimal notation. "#" may or may not be prepended to the string.
140
	 * @return string Color in hexadecimal notation on success - the string "transparent" otherwise.
141
	 */
142
	public static function sanitize_color_hex( $hex, $prefix = '#' ) {
143
		$hex = trim( $hex );
144
145
		/* Strip recognized prefixes. */
146
		if ( 0 === strpos( $hex, '#' ) )
147
			$hex = substr( $hex, 1 );
148
		elseif ( 0 === strpos( $hex, '%23' ) )
149
			$hex = substr( $hex, 3 );
150
151
		if ( 0 !== preg_match( '/^[0-9a-fA-F]{6}$/', $hex ) )
152
			return $prefix . $hex;
153
154
		return 'transparent';
155
	}
156
157
	/**
158
	 * Localize Front-end Script.
159
	 *
160
	 * Print the javascript configuration array only if the
161
	 * current template has an instance of the widget that
162
	 * is still counting down. In all other cases, this
163
	 * function will dequeue milestone.js.
164
	 *
165
     * Hooks into the "wp_footer" action.
166
     */
167
	function localize_script() {
168
		if ( empty( self::$config_js['instances'] ) ) {
169
			wp_dequeue_script( 'milestone' );
170
			return;
171
		}
172
		self::$config_js['labels'] = self::$labels;
173
		wp_localize_script( 'milestone', 'MilestoneConfig', self::$config_js );
174
	}
175
176
    /**
177
     * Widget
178
     */
179
    function widget( $args, $instance ) {
180
		$instance = $this->sanitize_instance( $instance );
181
182
		$milestone = mktime( $instance['hour'], $instance['min'], 0, $instance['month'], $instance['day'], $instance['year'] );
183
		$now  = (int) current_time( 'timestamp' );
184
		$diff = (int) floor( $milestone - $now );
185
186
		$number = 0;
0 ignored issues
show
Unused Code introduced by
$number is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
187
		$label  = '';
0 ignored issues
show
Unused Code introduced by
$label is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
188
189
		if ( 63113852 < $diff ) { // more than 2 years - show in years, one decimal point
190
			$number = round( $diff / 60 / 60 / 24 / 365, 1 );
191
			$label  = self::$labels['years'];
192
		} else if ( 7775999 < $diff ) { // fewer than 2 years - show in months
193
			$number = floor( $diff / 60 / 60 / 24 / 30 );
194
			$label  = ( 1 == $number ) ? self::$labels['month'] : self::$labels['months'];
195
		} else if ( 86399 < $diff ) { // fewer than 3 months - show in days
196
			$number = floor( $diff / 60 / 60 / 24 ) + 1;
197
			$label  = ( 1 == $number ) ? self::$labels['day'] : self::$labels['days'];
198
		} else if ( 3599 < $diff ) { // less than 1 day - show in hours
199
			$number = floor( $diff / 60 / 60 );
200
			$label  = ( 1 == $number ) ? self::$labels['hour'] : self::$labels['hours'];
201
		} else if ( 59 < $diff ) { // less than 1 hour - show in minutes
202
			$number = floor( $diff / 60 ) + 1;
203
			$label = ( 1 == $number ) ? self::$labels['minute'] : self::$labels['minutes'];
204
		} else { // less than 1 minute - show in seconds
205
			$number = $diff;
206
			$label = ( 1 == $number ) ? self::$labels['second'] : self::$labels['seconds'] ;
207
		}
208
209
		echo $args['before_widget'];
210
211
		$title = apply_filters( 'widget_title', $instance['title'] );
212
		if ( ! empty( $title ) )
213
			echo $args['before_title'] . $title . $args['after_title'];
214
215
		echo '<div class="milestone-content">';
216
217
		echo '<div class="milestone-header">';
218
		echo '<strong class="event">' . esc_html( $instance['event'] ) . '</strong>';
219
		echo '<span class="date">' . esc_html( date_i18n( __( 'F jS, Y' ), $milestone ) ) . '</span>';
220
		echo '</div>';
221
222
		if ( 1 > $diff ) {
223
			/* Milestone has past. */
224
			echo '<div class="milestone-message">' . $instance['message'] . '</div>';
225
		} else {
226
			/* Countdown to the milestone. */
227
			echo '<div class="milestone-countdown">' . sprintf( __( '%1$s %2$s to go.' ),
228
				'<span class="difference">' . esc_html( $number ) . '</span>',
229
				'<span class="label">' . esc_html( $label ) . '</span>'
230
			) . '</div>';
231
232
			self::$config_js['instances'][] = array(
233
				'id'      => $args['widget_id'],
234
				'diff'    => $diff,
235
				'message' => $instance['message'],
236
			);
237
		}
238
239
		echo '</div><!--milestone-content-->';
240
241
		echo $args['after_widget'];
242
243
	    /** This action is documented in modules/widgets/gravatar-profile.php */
244
	    do_action( 'jetpack_stats_extra', 'widget_view', 'milestone' );
245
    }
246
247
    /**
248
     * Update
249
     */
250
    function update( $new_instance, $old_instance ) {
251
		return $this->sanitize_instance( $new_instance );
252
    }
253
254
	/*
255
	 * Make sure that a number is within a certain range.
256
	 * If the number is too small it will become the possible lowest value.
257
	 * If the number is too large it will become the possible highest value.
258
	 *
259
	 * @param int $n The number to check.
260
	 * @param int $floor The lowest possible value.
261
	 * @param int $ceil The highest possible value.
262
	 */
263
	function sanitize_range( $n, $floor, $ceil ) {
264
		$n = (int) $n;
265
		if ( $n < $floor )
266
			$n = $floor;
267
		else if ( $n > $ceil )
268
			$n = $ceil;
269
		return $n;
270
	}
271
272
	/*
273
	 * Sanitize an instance of this widget.
274
	 *
275
	 * Date ranges match the documentation for mktime in the php manual.
276
	 * @see http://php.net/manual/en/function.mktime.php#refsect1-function.mktime-parameters
277
	 *
278
	 * @uses Milestone_Widget::sanitize_range().
279
	 */
280
	function sanitize_instance( $dirty ) {
281
		$now = (int) current_time( 'timestamp' );
282
283
		$dirty = wp_parse_args( $dirty, array(
284
			'title'   => '',
285
			'event'   => __( 'The Big Day' ),
286
			'message' => __( 'The big day is here.' ),
287
			'day'     => date( 'd', $now ),
288
			'month'   => date( 'm', $now ),
289
			'year'    => date( 'Y', $now ),
290
			'hour'    => 0,
291
			'min'     => 0,
292
		) );
293
294
		$allowed_tags = array(
295
			'a'      => array( 'title' => array(), 'href' => array() ),
296
			'em'     => array( 'title' => array() ),
297
			'strong' => array( 'title' => array() ),
298
		);
299
300
		$clean = array(
301
			'title'   => trim( strip_tags( stripslashes( $dirty['title'] ) ) ),
302
			'event'   => trim( strip_tags( stripslashes( $dirty['event'] ) ) ),
303
			'message' => wp_kses( $dirty['message'], $allowed_tags ),
304
			'year'    => $this->sanitize_range( $dirty['year'],  1901, 2037 ),
305
			'month'   => $this->sanitize_range( $dirty['month'], 1, 12 ),
306
			'hour'    => $this->sanitize_range( $dirty['hour'],  0, 23 ),
307
			'min'     => zeroise( $this->sanitize_range( $dirty['min'], 0, 59 ), 2 ),
308
		);
309
310
		$clean['day'] = $this->sanitize_range( $dirty['day'], 1, date( 't', mktime( 0, 0, 0, $clean['month'], 1, $clean['year'] ) ) );
311
312
		return $clean;
313
	}
314
315
    /**
316
     * Form
317
     */
318
    function form( $instance ) {
319
		$instance = $this->sanitize_instance( $instance );
320
        ?>
321
322
	<div class="milestone-widget">
323
        <p>
324
        	<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title' ); ?></label>
325
        	<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( $instance['title'] ); ?>" />
326
        </p>
327
328
        <p>
329
        	<label for="<?php echo $this->get_field_id( 'event' ); ?>"><?php _e( 'Event' ); ?></label>
330
        	<input class="widefat" id="<?php echo $this->get_field_id( 'event' ); ?>" name="<?php echo $this->get_field_name( 'event' ); ?>" type="text" value="<?php echo esc_attr( $instance['event'] ); ?>" />
331
        </p>
332
333
		<fieldset>
334
			<legend><?php _e( 'Date and Time' ); ?></legend>
335
336
			<label for="<?php echo $this->get_field_id( 'month' ); ?>" class="assistive-text"><?php _e( 'Month' ); ?></label>
337
			<select id="<?php echo $this->get_field_id( 'month' ); ?>" class="month" name="<?php echo $this->get_field_name( 'month' ); ?>"><?php
338
				global $wp_locale;
339
				for ( $i = 1; $i < 13; $i++ ) {
340
					$monthnum = zeroise( $i, 2 );
341
					echo '<option value="' . esc_attr( $monthnum ) . '"' . selected( $i, $instance['month'], false ) . '>' . $monthnum . '-' . $wp_locale->get_month_abbrev( $wp_locale->get_month( $i ) ) . '</option>';
342
				}
343
			?></select>
344
345
			<label for="<?php echo $this->get_field_id( 'day' ); ?>" class="assistive-text"><?php _e( 'Day' ); ?></label>
346
			<input id="<?php echo $this->get_field_id( 'day' ); ?>" class="day" name="<?php echo $this->get_field_name( 'day' ); ?>" type="text" value="<?php echo esc_attr( $instance['day'] ); ?>">,
347
348
			<label for="<?php echo $this->get_field_id( 'year' ); ?>" class="assistive-text"><?php _e( 'Year' ); ?></label>
349
			<input id="<?php echo $this->get_field_id( 'year' ); ?>" class="year" name="<?php echo $this->get_field_name( 'year' ); ?>" type="text" value="<?php echo esc_attr( $instance['year'] ); ?>">
350
351
			@ <label for="<?php echo $this->get_field_id( 'hour' ); ?>" class="assistive-text"><?php _e( 'Hour' ); ?></label>
352
			<input id="<?php echo $this->get_field_id( 'hour' ); ?>" class="hour" name="<?php echo $this->get_field_name( 'hour' ); ?>" type="text" value="<?php echo esc_attr( $instance['hour'] ); ?>">
353
354
			<label for="<?php echo $this->get_field_id( 'min' ); ?>" class="assistive-text"><?php _e( 'Minutes' ); ?></label>
355
			: <input id="<?php echo $this->get_field_id( 'min' ); ?>" class="minutes" name="<?php echo $this->get_field_name( 'min' ); ?>" type="text" value="<?php echo esc_attr( $instance['min'] ); ?>">
356
		</fieldset>
357
358
		<p>
359
			<label for="<?php echo $this->get_field_id( 'message' ); ?>"><?php _e( 'Message' ); ?></label>
360
			<textarea id="<?php echo $this->get_field_id( 'message' ); ?>" name="<?php echo $this->get_field_name( 'message' ); ?>" class="widefat"><?php echo esc_textarea( $instance['message'] ); ?></textarea>
361
		</p>
362
	</div>
363
364
		<?php
365
    }
366
}
367