Completed
Push — add/google-map-api-key-41 ( 19a69b )
by
unknown
35:08 queued 24:01
created

Jetpack_Contact_Info_Widget::build_map()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 10
nc 1
nop 2
dl 0
loc 14
rs 9.4285
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
			$google_url = 'https://maps.googleapis.com/maps/api/js?sensor=false';
46
			/**
47
			 * Set a Google Maps API Key.
48
			 *
49
			 * @since 4.1.0
50
			 *
51
			 * @param string $key Google Maps API Key
52
			 */
53
			$key = apply_filters( 'jetpack_google_maps_api_key', null );
54
55
			if ( ! empty( $key ) ) {
56
					$google_url = add_query_arg( 'key', $key, $google_url );
57
				}
58
59
			wp_enqueue_script( 'jquery' );
60
			wp_enqueue_script( 'google-maps', esc_url( $google_url ) );
61
			wp_enqueue_script( 'contact-info-map-js', plugins_url( 'contact-info/contact-info-map.js', __FILE__ ), array( 'jquery', 'google-maps' ), 20150127 );
62
			wp_enqueue_style( 'contact-info-map-css', plugins_url( 'contact-info/contact-info-map.css', __FILE__ ), null, 20150127 );
63
		}
64
65
		/**
66
		 * Return an associative array of default values
67
		 *
68
		 * These values are used in new widgets.
69
		 *
70
		 * @return array Array of default values for the Widget's options
71
		 */
72
		public function defaults() {
73
			return array(
74
				'title'   => __( 'Hours & Info', 'jetpack' ),
75
				'address' => __( "3999 Mission Boulevard,\nSan Diego CA 92109", 'jetpack' ),
76
				'phone'   => _x( '1-202-555-1212', 'Example of a phone number', 'jetpack' ),
77
				'hours'   => __( "Lunch: 11am - 2pm \nDinner: M-Th 5pm - 11pm, Fri-Sat:5pm - 1am", 'jetpack' ),
78
				'showmap' => 1,
79
				'lat'     => null,
80
				'lon'     => null
81
			);
82
		}
83
84
		/**
85
		 * Outputs the HTML for this widget.
86
		 *
87
		 * @param array $args     An array of standard parameters for widgets in this theme
88
		 * @param array $instance An array of settings for this widget instance
89
		 *
90
		 * @return void Echoes it's output
91
		 **/
92
		function widget( $args, $instance ) {
93
			$instance = wp_parse_args( $instance, $this->defaults() );
94
95
			echo $args['before_widget'];
96
97
			if ( '' != $instance['title'] ) {
98
				echo $args['before_title'] . $instance['title'] . $args['after_title'];
99
			}
100
101
			/**
102
			 * Fires at the beginning of the Contact Info widget, after the title.
103
			 *
104
			 * @module widgets
105
			 *
106
			 * @since 3.9.2
107
			 */
108
			do_action( 'jetpack_contact_info_widget_start' );
109
110
			if ( '' != $instance['address'] ) {
111
112
				$showmap = $instance['showmap'];
113
114
				if ( $showmap && $this->has_good_map( $instance ) ) {
115
116
					$lat = $instance['lat'];
117
					$lon = $instance['lon'];
118
119
					echo $this->build_map( $lat, $lon );
120
				}
121
122
				$map_link = $this->build_map_link( $instance['address'] );
123
124
				echo '<div class="confit-address"><a href="' . esc_url( $map_link ) . '" target="_blank">' . str_replace( "\n", "<br/>", esc_html( $instance['address'] ) ) . "</a></div>";
125
			}
126
127
			if ( '' != $instance['phone'] ) {
128
				if ( wp_is_mobile() ) {
129
					echo '<div class="confit-phone"><a href="' . esc_url( 'tel:' . $instance['phone'] ) . '">' . esc_html( $instance['phone'] ) . "</a></div>";
130
				}
131
				else {
132
					echo '<div class="confit-phone">' . esc_html( $instance['phone'] ) . '</div>';
133
				}
134
			}
135
136
			if ( '' != $instance['hours'] ) {
137
				echo '<div class="confit-hours">' . str_replace( "\n", "<br/>", esc_html( $instance['hours'] ) ) . "</div>";
138
			}
139
140
			/**
141
			 * Fires at the end of Contact Info widget.
142
			 *
143
			 * @module widgets
144
			 *
145
			 * @since 3.9.2
146
			 */
147
			do_action( 'jetpack_contact_info_widget_end' );
148
149
			echo $args['after_widget'];
150
		}
151
152
153
		/**
154
		 * Deals with the settings when they are saved by the admin. Here is
155
		 * where any validation should be dealt with.
156
		 *
157
		 * @param array $new_instance New configuration values
158
		 * @param array $old_instance Old configuration values
159
		 *
160
		 * @return array
161
		 */
162
		function update( $new_instance, $old_instance ) {
163
			$update_lat_lon = false;
164
			if (
165
				! isset( $old_instance['address'] ) ||
166
				$this->urlencode_address( $old_instance['address'] ) != $this->urlencode_address( $new_instance['address'] )
167
			) {
168
				$update_lat_lon = true;
169
			}
170
171
			$instance            = array();
172
			$instance['title']   = wp_kses( $new_instance['title'], array() );
173
			$instance['address'] = wp_kses( $new_instance['address'], array() );
174
			$instance['phone']   = wp_kses( $new_instance['phone'], array() );
175
			$instance['hours']   = wp_kses( $new_instance['hours'], array() );
176
			$instance['lat']     = isset( $old_instance['lat'] ) ? floatval( $old_instance['lat'] ) : 0;
177
			$instance['lon']     = isset( $old_instance['lon'] ) ? floatval( $old_instance['lon'] ) : 0;
178
179
			if ( ! $instance['lat'] || ! $instance['lon'] ) {
180
				$update_lat_lon = true;
181
			}
182
183
			if ( $instance['address'] && $update_lat_lon ) {
184
185
				// Get the lat/lon of the user specified address.
186
				$address = $this->urlencode_address( $instance['address'] );
187
				$path    = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=" . $address;
188
				/** This action is documented in modules/widgets/contact-info.php */
189
				$key = apply_filters( 'jetpack_google_maps_api_key', null );
190
191
				if ( ! empty( $key ) {
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected '{'
Loading history...
Bug introduced by
Avoid IF statements that are always true or false
Loading history...
192
					$path = add_query_arg( 'key', $key, $path );
193
				}
194
				$json    = wp_remote_retrieve_body( wp_remote_get( esc_url( $path ) ) );
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...
195
196
				if ( ! $json ) {
197
					// The read failed :(
198
					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' );
199
					die();
200
				}
201
202
				$json_obj = json_decode( $json );
203
204
				if ( "ZERO_RESULTS" == $json_obj->status ) {
205
					// The address supplied does not have a matching lat / lon.
206
					// No map is available.
207
					$instance['lat'] = "0";
208
					$instance['lon'] = "0";
209
				}
210
				else {
211
212
					$loc = $json_obj->results[0]->geometry->location;
213
214
					$lat = floatval( $loc->lat );
215
					$lon = floatval( $loc->lng );
216
217
					$instance['lat'] = "$lat";
218
					$instance['lon'] = "$lon";
219
				}
220
			}
221
222
			if ( ! isset( $new_instance['showmap'] ) ) {
223
				$instance['showmap'] = 0;
224
			}
225
			else {
226
				$instance['showmap'] = intval( $new_instance['showmap'] );
227
			}
228
229
			return $instance;
230
		}
231
232
233
		/**
234
		 * Displays the form for this widget on the Widgets page of the WP Admin area.
235
		 *
236
		 * @param array $instance Instance configuration.
237
		 *
238
		 * @return void
239
		 */
240
		function form( $instance ) {
241
			$instance = wp_parse_args( $instance, $this->defaults() );
242
			?>
243
			<p>
244
				<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_html_e( 'Title:', 'jetpack' ); ?></label>
245
				<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'] ); ?>" />
246
			</p>
247
248
			<p>
249
				<label for="<?php echo esc_attr( $this->get_field_id( 'address' ) ); ?>"><?php esc_html_e( 'Address:', 'jetpack' ); ?></label>
250
				<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>
251
				<?php
252
				if ( $this->has_good_map( $instance ) ) {
253
					?>
254
					<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 ); ?> />
255
					<label for="<?php echo esc_attr( $this->get_field_id( 'showmap' ) ); ?>"><?php esc_html_e( 'Show map', 'jetpack' ); ?></label>
256
					<?php
257
				}
258
				else {
259
					?>
260
					<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>
261
					<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" />
262
					<?php
263
				}
264
				?>
265
			</p>
266
			<p>
267
				<label for="<?php echo esc_attr( $this->get_field_id( 'phone' ) ); ?>"><?php esc_html_e( 'Phone:', 'jetpack' ); ?></label>
268
				<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'] ); ?>" />
269
			</p>
270
271
			<p>
272
				<label for="<?php echo esc_attr( $this->get_field_id( 'hours' ) ); ?>"><?php esc_html_e( 'Hours:', 'jetpack' ); ?></label>
273
				<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>
274
			</p>
275
276
			<?php
277
		}
278
279
280
		/**
281
		 * Generate a Google Maps link for the supplied address.
282
		 *
283
		 * @param string $address Address to link to.
284
		 *
285
		 * @return string
286
		 */
287
		function build_map_link( $address ) {
288
			// Google map urls have lots of available params but zoom (z) and query (q) are enough.
289
			return "http://maps.google.com/maps?z=16&q=" . $this->urlencode_address( $address );
290
		}
291
292
293
		/**
294
		 * Builds map display HTML code from the supplied latitude and longitude.
295
		 *
296
		 * @param float $lat Map Latitude
297
		 * @param float $lon Map Longitude
298
		 *
299
		 * @return string HTML of the map
300
		 */
301
		function build_map( $lat, $lon ) {
302
			$this->enqueue_scripts();
303
304
			$lat  = esc_attr( $lat );
305
			$lon  = esc_attr( $lon );
306
			$html = <<<EOT
307
				<div class="contact-map">
308
				<input type="hidden" class="contact-info-map-lat" value="$lat" />
309
				<input type="hidden" class="contact-info-map-lon" value="$lon" />
310
				<div class="contact-info-map-canvas"></div></div>
311
EOT;
312
313
			return $html;
314
		}
315
316
		/**
317
		 * Encode an URL
318
		 *
319
		 * @param string $address The URL to encode
320
		 *
321
		 * @return string The encoded URL
322
		 */
323
		function urlencode_address( $address ) {
324
325
			$address = strtolower( $address );
326
			$address = preg_replace( "/\s+/", " ", trim( $address ) ); // Get rid of any unwanted whitespace
327
			$address = str_ireplace( " ", "+", $address ); // Use + not %20
328
			urlencode( $address );
329
330
			return $address;
331
		}
332
333
		/**
334
		 * Check if the instance has a valid Map location.
335
		 *
336
		 * @param array $instance Widget instance configuration.
337
		 *
338
		 * @return bool Whether or not there is a valid map.
339
		 */
340
		function has_good_map( $instance ) {
341
			// The lat and lon of an address that could not be plotted will have values of 0 and 0.
342
			return ! ( "0" == $instance['lat'] && "0" == $instance['lon'] );
343
		}
344
345
	}
346
347
}
348