PluginProbe
Event Post / 5.0
Event Post v5.0
6.1.1 6.1.0 6.0.1 6.0.0 5.12.0 trunk 3.9 4.0 4.2 4.3 4.4 4.5 5.0 5.1 5.10.0 5.10.1 5.10.2 5.10.3 5.10.4 5.11.0 5.11.1 5.2 5.5 5.6 5.6.1 All 46 releases
event-post / inc / openweathermap.php

openweathermap.php in Event Post 5.0, at inc/openweathermap.php

495 lines 16.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 $EventPostWeather = new EventPostWeather();
3
4 /**
5 * Provides weather support thanks to OpenWeatherMap
6 * http://openweathermap.org
7 *
8 * License: Creative Commons (cc-by-sa)
9 * http://creativecommons.org/licenses/by-sa/2.0/.
10 *
11 *
12 * Get an API key
13 * http://openweathermap.org/appid#get
14 *
15 */
16 class EventPostWeather {
17
18 var $META_WEATHER;
19
20 var $api_key;
21 var $units;
22 var $unit_names;
23 var $theme;
24
25 function __construct() {
26 // Hook into the plugin
27
28 add_action('eventpost_getsettings_action', array(&$this, 'get_settings'), 1, 2);
29 add_action('eventpost_settings_form', array(&$this, 'settings_form'));
30 add_action('evenpost_init', array(&$this, 'init'));
31 }
32
33 /**
34 * PHP4 constructor
35 */
36 function EventPostWeather() {
37 $this->__construct();
38 }
39
40 /**
41 * Only for localization
42 *
43 * available values:
44 *
45 * - clear sky
46 * - few clouds
47 * - scattered clouds
48 * - broken clouds
49 * - shower rain
50 * - rain
51 * - thunderstorm
52 * - snow
53 * - mist
54 */
55 function localize(){
56 __('clear sky', 'event-post');
57 __('few clouds', 'event-post');
58 __('scattered clouds', 'event-post');
59 __('broken clouds', 'event-post');
60 __('shower rain', 'event-post');
61 __('rain', 'event-post');
62 __('thunderstorm', 'event-post');
63 __('snow', 'event-post');
64 __('mist', 'event-post');
65
66 }
67
68 /**
69 *
70 * @param array reference &$ep_settings
71 * @param boolean reference &$reg_settings
72 */
73 function get_settings(&$ep_settings, &$reg_settings) {
74 if (!isset($ep_settings['weather_enabled'])) {
75 $ep_settings['weather_enabled'] = false;
76 $reg_settings = true;
77 }
78 if (!isset($ep_settings['weather_api_key'])) {
79 $ep_settings['weather_api_key'] = '';
80 $reg_settings = true;
81 }
82 if (!isset($ep_settings['weather_units'])) {
83 $ep_settings['weather_units'] = 'standard';
84 $reg_settings = true;
85 }
86 }
87
88 /**
89 *
90 * @param type $ep_settings
91 */
92 function settings_form($ep_settings) {
93 ?>
94 <h2><?php _e('Weather', 'event-post'); ?></h2>
95 <p class="description"><?php printf(__('Provided thanks to %s', 'event-post'), '<a href="http://openweathermap.org" target="_blank">openweathermap.org</a>'); ?></p>
96 <table class="form-table" id="eventpost-settings-table-weather">
97 <tbody>
98 <tr>
99 <th>
100 <?php _e('Enable weather', 'event-post') ?>
101 </th>
102 <td>
103 <label for="weather_enabled">
104 <input type="checkbox" name="ep_settings[weather_enabled]" id="weather_enabled" <?php if ($ep_settings['weather_enabled'] == '1') {
105 echo'checked';
106 } ?> value="1">
107 <?php _e('Enable weather feature', 'event-post') ?>
108 </label>
109 </td>
110 </tr>
111 <tr>
112 <th>
113 <label for="weather_api_key">
114 <?php _e('API key', 'event-post') ?>
115 </label>
116 </th>
117 <td>
118 <input type="text" name="ep_settings[weather_api_key]" id="weather_api_key" value="<?php echo $ep_settings['weather_api_key']; ?>" size="40">
119 <p class="description"><?php printf(__('Get a free API key at: %s', 'event-post'), '<a href="http://openweathermap.org/appid#get" target="_blank">openweathermap.org/appid#get</a>'); ?></p>
120 </td>
121 </tr>
122 <tr>
123 <th>
124 <label for="weather_units">
125 <?php _e('Units', 'event-post') ?>
126 </label>
127 </th>
128 <td>
129 <select name="ep_settings[weather_units]" id="weather_units">
130 <option value="standard" <?php selected($ep_settings['weather_units'], 'standard', true);?>>
131 <?php _e('Standard (Fahrenheit)', 'event-post') ?>
132 </option>
133 <option value="metric" <?php selected($ep_settings['weather_units'], 'metric', true);?>>
134 <?php _e('Metric (Celsius)', 'event-post') ?>
135 </option>
136 <option value="imperial" <?php selected($ep_settings['weather_units'], 'imperial', true);?>>
137 <?php _e('Imperial (Kelvin)', 'event-post') ?>
138 </option>
139 </select>
140 </td>
141 </tr>
142 </tbody>
143 </table><!-- #eventpost-settings-table-weather -->
144 <?php
145 }
146
147 /**
148 *
149 * @param object $EP
150 * @return void
151 */
152 function init($EP) {
153 // Ensure OpenWeatherMap is required and available.
154 if (!$EP->settings['weather_enabled'] || !$EP->settings['weather_api_key']) {
155 return;
156 }
157
158 $this->META_WEATHER = 'event_weather';
159 $this->api_key = $EP->settings['weather_api_key'];
160 $this->units = $EP->settings['weather_units'];
161 $this->theme = 'default';
162 $this->unit_names = array('standard'=>'F', 'metric'=>'C', 'imperial'=>'K');
163
164 // Alter objects
165 add_filter('eventpost_params', array(&$this, 'params'));
166 add_filter('eventpost_retreive', array(&$this, 'retreive'));
167
168 // Alter schema
169 add_filter('eventpost_item_scheme_entities', array(&$this, 'scheme_entities'));
170 add_filter('eventpost_item_scheme_values', array(&$this, 'scheme_values'), 1, 2);
171 add_filter('eventpost_default_list_shema', array(&$this, 'default_shema'));
172 add_filter('eventpost_get_single', array(&$this, 'get_single'), 1, 2);
173
174
175 add_action('eventpost_custom_box_date', array(&$this, 'get_weather'));
176
177
178 }
179
180 /**
181 *
182 * @param array $params
183 * @return array
184 */
185 function params($params = array()) {
186 $params['weather'] = true;
187 return $params;
188 }
189
190 /**
191 *
192 * @param WP_Post $event
193 * @return WP_Post
194 */
195 function retreive($event) {
196 $event->weather = get_post_meta($event->ID, $this->META_WEATHER, true);
197 return $event;
198 }
199
200 /**
201 *
202 * @param array $attr
203 * @return array
204 */
205 function scheme_entities($attr = array()) {
206 array_push($attr, '%event_weather%');
207 return $attr;
208 }
209
210 /**
211 *
212 * @param array $values
213 * @return array
214 */
215 function scheme_values($values = array(), $post = null) {
216 array_push($values, $this->get_weather($post));
217 return $values;
218 }
219
220 /**
221 *
222 * @param array $schema
223 * @return array
224 */
225 function default_shema($schema) {
226 $schema['item'] = str_replace('</%child%>', "%event_weather%\n</%child%>", $schema['item']);
227 return $schema;
228 }
229
230 function get_single($event_datas, $post = null) {
231 return $event_datas . $this->get_weather($post);
232 }
233
234 /**
235 * From here, methods intends to get datas
236 */
237
238 function get_weather_icons($weather){
239 $string = '';
240 foreach((array) $weather as $item){
241 $text = ucfirst(__(strtolower($item->description), 'event-post'));
242 $string.='<span class="eventpost-weather-'.str_replace('-', '', strtolower($item->description)).' eventpost-weather-'.$item->icon.'">'
243 . '<img src="'. plugins_url('../img/weather/'.$this->theme.'/'.$item->icon.'.png', __FILE__).'" alt="'.sprintf('%s icon', $text).'">'
244 . '<em class="eventpost-weather-text">'.$text.'</em>'
245 . '</span>';
246 }
247 return $string;
248 }
249 /**
250 *
251 * @param object $item
252 * @return string
253 */
254 function get_weather_item($item){
255 $string = '';
256 $string.= '<div class="eventpost-weather-item">'
257 .'<span class="eventpost-weather-date">'.date_i18n(get_option('date_format').' '.get_option('time_format'), $item->dt).'</span> '
258 .'<span class="eventpost-weather-temp">'.round($item->main->temp).' &deg'.$this->unit_names[$this->units].'</span> '
259 .'<span class="eventpost-weather-list">'.$this->get_weather_icons($item->weather).'</span>'
260 .'</div>';
261 return $string;
262 }
263
264 /**
265 *
266 * @param type $post
267 * @return string
268 */
269 function get_weather($post = null, $echo=false) {
270 global $EventPost;
271 $event = $EventPost->retreive($post);
272 if(false === $weather = $this->get_weather_datas($event)){
273 return '';
274 }
275 if(false == $weather['data']){
276 return '';
277 }
278
279 $string='';
280
281 switch ($weather['type']){
282 case 'current':
283 $string.=$this->get_weather_item($weather['data']);
284 break;
285 case 'history':
286 if(!isset($weather['data']->list) || !is_array($weather['data']->list)){
287 break;
288 }
289 foreach($weather['data']->list as $day){
290 if($day->dt >= $event->time_start && $day->dt <= $event->time_end){
291 $string.=$this->get_weather_item($day);
292 }
293 }
294 break;
295 case 'forecast':
296 if(!is_array($weather['data']->list)){
297 break;
298 }
299 foreach($weather['data']->list as $day){
300 if($day->dt >= $event->time_start && $day->dt <= $event->time_end){
301 $string.=$this->get_weather_item($day);
302 }
303 }
304 break;
305 }
306 if($echo){
307 echo $string;
308 }
309 return $string;
310 }
311
312 /**
313 *
314 * @param type $event
315 * @return type
316 */
317 function get_weather_datas($event){
318 if (!$event->lat || !$event->long || !is_numeric($event->time_start) || !is_numeric($event->time_end)) {
319 return false;
320 }
321
322 $now = current_time('timestamp');
323 $local_weather = $event->weather;
324
325
326
327 // Datas are allready stored, we probably won't get better ones.
328 if(is_array($local_weather) && $local_weather['data'] && ($local_weather['type']=='current' || $local_weather['type']=='history')){
329 return $local_weather;
330 }
331
332 // Finally, we have to fetch datas...
333 $weather = array('type'=>false, 'data'=>false);
334
335 // For Current and history results, we definitly store datas
336 if ( $event->time_start<= $now && $event->time_end>=$now) {
337 $weather = array('type'=>'current', 'data'=>$this->get_current($event), 'fetched'=>time());
338 update_post_meta($event->ID, $this->META_WEATHER, $weather);
339 }
340 elseif ( $event->time_end<$now) {// History
341 $weather = array('type'=>'history', 'data'=>$this->get_history($event), 'fetched'=>time());
342 update_post_meta($event->ID, $this->META_WEATHER, $weather);
343 }
344 else {
345 // Forecast datas are only stored in cache for 24 hours
346 $transient_name = 'eventpost_weather_' . $event->ID;
347 $weather = get_transient($transient_name);
348 if (false === $weather || empty($weather)) {
349 $weather = array('type'=>'forecast', 'data'=>$this->get_forecast($event), 'fetched'=>time());
350 set_transient($transient_name, $weather, 1 * DAY_IN_SECONDS);
351 }
352 }
353 return $weather;
354 }
355
356
357 /**
358 * Generates the URL to call the API
359 * @param type $method
360 * @param type $params
361 * @return type
362 */
363 function get_url($method = 'weather', $params = array()) {
364 $params['APPID']= $this->api_key;
365 $params['units']= $this->units;
366 return 'http://api.openweathermap.org/data/2.5/' . $method . '?' . http_build_query($params);
367 }
368
369 /**
370 * ### current
371 * http://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&APPID=XXXX
372 *
373 * return:
374 *
375 {"coord":{"lon":139,"lat":35},
376 "sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},
377 "weather":[{"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}],
378 "main":{"temp":289.5,"humidity":89,"pressure":1013,"temp_min":287.04,"temp_max":292.04},
379 "wind":{"speed":7.31,"deg":187.002},
380 "rain":{"3h":0},
381 "clouds":{"all":92},
382 "dt":1369824698,
383 "id":1851632,
384 "name":"Shuzenji",
385 "cod":200}
386 *
387 * @param type $event
388 * @return object
389 */
390 function get_current($event){
391 if (!$event->lat || !$event->long) {
392 return;
393 }
394 return json_decode(wp_remote_retrieve_body(
395 wp_remote_get(
396 $this-> get_url('weather', array(
397 'lat' => $event->lat,
398 'lon' => $event->long,
399 ))
400 )
401 ));
402 }
403
404 /**
405 * ### forecast
406 * api.openweathermap.org/data/2.5/forecast?lat={lat}&lon={lon}&APPID=XXXX
407 *
408 * return:
409 *
410 {"city":{"id":1851632,"name":"Shuzenji",
411 "coord":{"lon":138.933334,"lat":34.966671},
412 "country":"JP",
413 "cod":"200",
414 "message":0.0045,
415 "cnt":38,
416 "list":[{
417 "dt":1406106000,
418 "main":{
419 "temp":298.77,
420 "temp_min":298.77,
421 "temp_max":298.774,
422 "pressure":1005.93,
423 "sea_level":1018.18,
424 "grnd_level":1005.93,
425 "humidity":87
426 "temp_kf":0.26},
427 "weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],
428 "clouds":{"all":88},
429 "wind":{"speed":5.71,"deg":229.501},
430 "sys":{"pod":"d"},
431 "dt_txt":"2014-07-23 09:00:00"}
432 ]}
433 *
434 * @param type $event
435 * @return type
436 */
437 function get_forecast($event){
438 if (!$event->lat || !$event->long) {
439 return;
440 }
441 return json_decode(wp_remote_retrieve_body(
442 wp_remote_get(
443 $this-> get_url('forecast', array(
444 'lat' => $event->lat,
445 'lon' => $event->long,
446 ))
447 )
448 ));
449 }
450
451 /**
452 * ### history
453 * http://api.openweathermap.org/data/2.5/history/city?lat={lat}&lon={lon}&type=hour&start={start}&end={end}&APPID=XXXX
454 *
455 * Parameters:
456 * lat, lon coordinates of the location of your interest
457 * type type of the call, keep this parameter in the API call as 'hour'
458 * start start date (unix time, UTC time zone), e.g. start=1369728000
459 * end end date (unix time, UTC time zone), e.g. end=1369789200
460 * cnt amount of returned data (one per hour, can be used instead of 'end') *
461 *
462 * return:
463 {"message":"","cod":"200","type":"tick","station_id":39419,"cnt":30,
464 "list":[
465 {"dt":1345291920,
466 "main":{"temp":291.55,"humidity":95,"pressure":1009.3},
467 "wind":{"speed":0,"gust":0.3},
468 "rain":{"1h":0.6,"today":2.7},
469 "calc":{"dewpoint":17.6} }
470 ]}
471 *
472 *
473 * @param type $event
474 * @return type
475 */
476 function get_history($event) {
477 if (!$event->start || !$event->end || !$event->lat || !$event->long) {
478 return;
479 }
480 $history = json_decode(wp_remote_retrieve_body(
481 wp_remote_get(
482 $this-> get_url('history/city', array(
483 'lat' => $event->lat,
484 'lon' => $event->long,
485 'start' => $event->time_start,
486 'end' => $event->time_end,
487 'type' => 'hour',
488 ))
489 )
490 ));
491 return $history ? $history : (object) array('result'=>false);
492 }
493
494 }
495