Completed
Push — fix/space-twitter-4455 ( 859b70...d25e05 )
by Jeremy
20:31 queued 11:02
created

Jetpack_Contact_Info_Widget::build_map_link()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
if ( ! class_exists( 'Jetpack_Contact_Info_Widget' ) ) {
4
5
	//register Contact_Info_Widget widget
6
	function jetpack_contact_info_widget_init() {
7
		register_widget( 'Jetpack_Contact_Info_Widget' );
8
	}
9
10
	add_action( 'widgets_init', 'jetpack_contact_info_widget_init' );
11
12
	/**
13
	 * Makes a custom Widget for displaying Resturant Location, Hours and Contact Info available.
14
	 *
15
	 * @package WordPress
16
	 */
17
	class Jetpack_Contact_Info_Widget extends WP_Widget {
18
19
		/**
20
		 * Constructor
21
		 */
22
		function __construct() {
23
			$widget_ops = array(
24
				'classname' => 'widget_contact_info',
25
				'description' => __( 'Display your location, hours, and contact information.', 'jetpack' ),
26
				'customize_selective_refresh' => true,
27
			);
28
			parent::__construct(
29
				'widget_contact_info',
30
				/** This filter is documented in modules/widgets/facebook-likebox.php */
31
				apply_filters( 'jetpack_widget_name', __( 'Contact Info', 'jetpack' ) ),
32
				$widget_ops
33
			);
34
			$this->alt_option_name = 'widget_contact_info';
35
36
			if ( is_customize_preview() ) {
37
				add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
38
			}
39
		}
40
41
		/**
42
		 * Enqueue scripts and styles.
43
		 */
44
		public function enqueue_scripts() {
45
			wp_enqueue_style( 'contact-info-map-css', plugins_url( 'contact-info/contact-info-map.css', __FILE__ ), null, 20160623 );
46
		}
47
48
49
		/**
50
		 * Return an associative array of default values
51
		 *
52
		 * These values are used in new widgets.
53
		 *
54
		 * @return array Array of default values for the Widget's options
55
		 */
56
		public function defaults() {
57
			return array(
58
				'title'   => __( 'Hours & Info', 'jetpack' ),
59
				'address' => __( "3999 Mission Boulevard,\nSan Diego CA 92109", 'jetpack' ),
60
				'phone'   => _x( '1-202-555-1212', 'Example of a phone number', 'jetpack' ),
61
				'hours'   => __( "Lunch: 11am - 2pm \nDinner: M-Th 5pm - 11pm, Fri-Sat:5pm - 1am", 'jetpack' ),
62
				'showmap' => 1,
63
				'lat'     => null,
64
				'lon'     => null
65
			);
66
		}
67
68
		/**
69
		 * Outputs the HTML for this widget.
70
		 *
71
		 * @param array $args     An array of standard parameters for widgets in this theme
72
		 * @param array $instance An array of settings for this widget instance
73
		 *
74
		 * @return void Echoes it's output
75
		 **/
76
		function widget( $args, $instance ) {
77
			$instance = wp_parse_args( $instance, $this->defaults() );
78
79
			echo $args['before_widget'];
80
81
			if ( '' != $instance['title'] ) {
82
				echo $args['before_title'] . $instance['title'] . $args['after_title'];
83
			}
84
85
			/**
86
			 * Fires at the beginning of the Contact Info widget, after the title.
87
			 *
88
			 * @module widgets
89
			 *
90
			 * @since 3.9.2
91
			 */
92
			do_action( 'jetpack_contact_info_widget_start' );
93
94
			if ( '' != $instance['address'] ) {
95
96
				$showmap = $instance['showmap'];
97
98
				/** This action is documented in modules/widgets/contact-info.php */
99
				if ( $showmap && $this->has_good_map( $instance ) && apply_filters( 'jetpack_google_maps_api_key', null ) ) {
100
					echo $this->build_map( $instance['address'] );
101
				}
102
103
				$map_link = $this->build_map_link( $instance['address'] );
104
105
				echo '<div class="confit-address"><a href="' . esc_url( $map_link ) . '" target="_blank">' . str_replace( "\n", "<br/>", esc_html( $instance['address'] ) ) . "</a></div>";
106
			}
107
108
			if ( '' != $instance['phone'] ) {
109
				if ( wp_is_mobile() ) {
110
					echo '<div class="confit-phone"><a href="' . esc_url( 'tel:' . $instance['phone'] ) . '">' . esc_html( $instance['phone'] ) . "</a></div>";
111
				}
112
				else {
113
					echo '<div class="confit-phone">' . esc_html( $instance['phone'] ) . '</div>';
114
				}
115
			}
116
117
			if ( '' != $instance['hours'] ) {
118
				echo '<div class="confit-hours">' . str_replace( "\n", "<br/>", esc_html( $instance['hours'] ) ) . "</div>";
119
			}
120
121
			/**
122
			 * Fires at the end of Contact Info widget.
123
			 *
124
			 * @module widgets
125
			 *
126
			 * @since 3.9.2
127
			 */
128
			do_action( 'jetpack_contact_info_widget_end' );
129
130
			echo $args['after_widget'];
131
		}
132
133
134
		/**
135
		 * Deals with the settings when they are saved by the admin. Here is
136
		 * where any validation should be dealt with.
137
		 *
138
		 * @param array $new_instance New configuration values
139
		 * @param array $old_instance Old configuration values
140
		 *
141
		 * @return array
142
		 */
143
		function update( $new_instance, $old_instance ) {
144
			$update_lat_lon = false;
145
			if (
146
				! isset( $old_instance['address'] ) ||
147
				$this->urlencode_address( $old_instance['address'] ) != $this->urlencode_address( $new_instance['address'] )
148
			) {
149
				$update_lat_lon = true;
150
			}
151
152
			$instance            = array();
153
			$instance['title']   = wp_kses( $new_instance['title'], array() );
154
			$instance['address'] = wp_kses( $new_instance['address'], array() );
155
			$instance['phone']   = wp_kses( $new_instance['phone'], array() );
156
			$instance['hours']   = wp_kses( $new_instance['hours'], array() );
157
			$instance['lat']     = isset( $old_instance['lat'] ) ? floatval( $old_instance['lat'] ) : 0;
158
			$instance['lon']     = isset( $old_instance['lon'] ) ? floatval( $old_instance['lon'] ) : 0;
159
160
			if ( ! $instance['lat'] || ! $instance['lon'] ) {
161
				$update_lat_lon = true;
162
			}
163
164
			if ( $instance['address'] && $update_lat_lon ) {
165
166
				// Get the lat/lon of the user specified address.
167
				$address = $this->urlencode_address( $instance['address'] );
168
				$path    = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=" . $address;
169
				/** This action is documented in modules/widgets/contact-info.php */
170
				$key = apply_filters( 'jetpack_google_maps_api_key', null );
171
172
				if ( ! empty( $key ) ) {
173
					$path = add_query_arg( 'key', $key, $path );
174
				}
175
				$json    = wp_remote_retrieve_body( wp_remote_get( esc_url( $path, null, null ) ) );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 4 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
176
177
				if ( ! $json ) {
178
					// The read failed :(
179
					esc_html_e( "There was a problem getting the data to display this address on a map.  Please refresh your browser and try again.", 'jetpack' );
180
					die();
0 ignored issues
show
Coding Style Compatibility introduced by
The method update() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
181
				}
182
183
				$json_obj = json_decode( $json );
184
185
				if ( "ZERO_RESULTS" == $json_obj->status ) {
186
					// The address supplied does not have a matching lat / lon.
187
					// No map is available.
188
					$instance['lat'] = "0";
189
					$instance['lon'] = "0";
190
				}
191
				else {
192
193
					$loc = $json_obj->results[0]->geometry->location;
194
195
					$lat = floatval( $loc->lat );
196
					$lon = floatval( $loc->lng );
197
198
					$instance['lat'] = "$lat";
199
					$instance['lon'] = "$lon";
200
				}
201
			}
202
203
			if ( ! isset( $new_instance['showmap'] ) ) {
204
				$instance['showmap'] = 0;
205
			}
206
			else {
207
				$instance['showmap'] = intval( $new_instance['showmap'] );
208
			}
209
210
			return $instance;
211
		}
212
213
214
		/**
215
		 * Displays the form for this widget on the Widgets page of the WP Admin area.
216
		 *
217
		 * @param array $instance Instance configuration.
218
		 *
219
		 * @return void
220
		 */
221
		function form( $instance ) {
222
			$instance = wp_parse_args( $instance, $this->defaults() );
223
			?>
224
			<p>
225
				<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_html_e( 'Title:', 'jetpack' ); ?></label>
226
				<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $instance['title'] ); ?>" />
227
			</p>
228
229
			<p>
230
				<label for="<?php echo esc_attr( $this->get_field_id( 'address' ) ); ?>"><?php esc_html_e( 'Address:', 'jetpack' ); ?></label>
231
				<textarea class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'address' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'address' ) ); ?>"><?php echo esc_textarea( $instance['address'] ); ?></textarea>
232
				<?php
233
				if ( $this->has_good_map( $instance ) ) {
234
					?>
235
					<input class="" id="<?php echo esc_attr( $this->get_field_id( 'showmap' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'showmap' ) ); ?>" value="1" type="checkbox" <?php checked( $instance['showmap'], 1 ); ?> />
236
					<label for="<?php echo esc_attr( $this->get_field_id( 'showmap' ) ); ?>"><?php esc_html_e( 'Show map', 'jetpack' ); ?></label>
237
					<?php
238
				}
239
				else {
240
					?>
241
					<span class="error-message"><?php _e( 'Sorry. We can not plot this address. A map will not be displayed. Is the address formatted correctly?', 'jetpack' ); ?></span>
242
					<input id="<?php echo esc_attr( $this->get_field_id( 'showmap' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'showmap' ) ); ?>" value="<?php echo( intval( $instance['showmap'] ) ); ?>" type="hidden" />
243
					<?php
244
				}
245
				?>
246
			</p>
247
			<p>
248
				<label for="<?php echo esc_attr( $this->get_field_id( 'phone' ) ); ?>"><?php esc_html_e( 'Phone:', 'jetpack' ); ?></label>
249
				<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'phone' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'phone' ) ); ?>" type="text" value="<?php echo esc_attr( $instance['phone'] ); ?>" />
250
			</p>
251
252
			<p>
253
				<label for="<?php echo esc_attr( $this->get_field_id( 'hours' ) ); ?>"><?php esc_html_e( 'Hours:', 'jetpack' ); ?></label>
254
				<textarea class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'hours' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'hours' ) ); ?>"><?php echo esc_textarea( $instance['hours'] ); ?></textarea>
255
			</p>
256
257
			<?php
258
		}
259
260
261
		/**
262
		 * Generate a Google Maps link for the supplied address.
263
		 *
264
		 * @param string $address Address to link to.
265
		 *
266
		 * @return string
267
		 */
268
		function build_map_link( $address ) {
269
			// Google map urls have lots of available params but zoom (z) and query (q) are enough.
270
			return "http://maps.google.com/maps?z=16&q=" . $this->urlencode_address( $address );
271
		}
272
273
274
		/**
275
		 * Builds map display HTML code from the supplied latitude and longitude.
276
		 *
277
		 * @param float $lat Map Latitude
0 ignored issues
show
Bug introduced by
There is no parameter named $lat. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

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

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

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

Loading history...
278
		 * @param float $lon Map Longitude
0 ignored issues
show
Bug introduced by
There is no parameter named $lon. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

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

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

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

Loading history...
279
		 *
280
		 * @return string HTML of the map
281
		 */
282
		function build_map( $address ) {
283
			$this->enqueue_scripts();
284
			$src = add_query_arg( 'q', urlencode( $address ), 'https://www.google.com/maps/embed/v1/place' );
285
			/**
286
			 * Set a Google Maps API Key.
287
			 *
288
			 * @since 4.1.0
289
			 *
290
			 * @param string $key Google Maps API Key
291
			 */
292
			$key = apply_filters( 'jetpack_google_maps_api_key', null );
293
			if ( ! empty( $key ) ) {
294
				$src = add_query_arg( 'key', $key, $src );
295
			}
296
297
			return '<iframe width="600" height="216" frameborder="0" src="' . esc_url( $src ) . '" class="contact-map"></iframe>';
298
		}
299
300
		/**
301
		 * Encode an URL
302
		 *
303
		 * @param string $address The URL to encode
304
		 *
305
		 * @return string The encoded URL
306
		 */
307
		function urlencode_address( $address ) {
308
309
			$address = strtolower( $address );
310
			$address = preg_replace( "/\s+/", " ", trim( $address ) ); // Get rid of any unwanted whitespace
311
			$address = str_ireplace( " ", "+", $address ); // Use + not %20
312
			urlencode( $address );
313
314
			return $address;
315
		}
316
317
		/**
318
		 * Check if the instance has a valid Map location.
319
		 *
320
		 * @param array $instance Widget instance configuration.
321
		 *
322
		 * @return bool Whether or not there is a valid map.
323
		 */
324
		function has_good_map( $instance ) {
325
			// The lat and lon of an address that could not be plotted will have values of 0 and 0.
326
			return ! ( "0" == $instance['lat'] && "0" == $instance['lon'] );
327
		}
328
329
	}
330
331
}
332