PluginProbe
Event Post / 5.6.1
Event Post v5.6.1
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.6.1, at inc/openweathermap.php

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