6197c96174c746895189aba5ce79c88febb80efc
[friendica-addons.git] / curweather / curweather.php
1 <?php
2 /**
3  * Name: Current Weather 
4  * Description: Shows current weather conditions for user's location on their network page.
5  * Version: 1.1
6  * Author: Tony Baldwin <http://friendica.tonybaldwin.info/u/t0ny>
7  * Author: Fabio Comuni <http://kirkgroup.com/u/fabrixxm>
8  * Author: Tobias Diekershoff <https://f.diekershoff.de/u/tobias>
9  *
10  */
11
12 require_once('include/network.php');
13 require_once("mod/proxy.php");
14 require_once('include/text.php');
15
16 use Friendica\Core\Cache;
17 use Friendica\Core\Config;
18 use Friendica\Core\PConfig;
19
20 //  get the weather data from OpenWeatherMap
21 function getWeather( $loc, $units='metric', $lang='en', $appid='', $cachetime=0) {
22     $url = "http://api.openweathermap.org/data/2.5/weather?q=".$loc."&appid=".$appid."&lang=".$lang."&units=".$units."&mode=xml";
23     $cached = Cache::get('curweather'.md5($url));
24     $now = new DateTime();
25     if (!is_null($cached)) {
26         $cdate = PConfig::get(local_user(), 'curweather', 'last');
27         $cached = unserialize($cached);
28         if ($cdate + $cachetime > $now->getTimestamp()) {
29             return $cached;
30         }
31     }
32     try {
33         $res = new SimpleXMLElement(fetch_url($url));
34     } catch (Exception $e) {
35         info(t('Error fetching weather data.\nError was: '.$e->getMessage()));
36         return false;
37     }
38     if ((string)$res->temperature['unit']==='metric') {
39         $tunit = '°C';
40         $wunit = 'm/s';
41     } else {
42         $tunit = '°F';
43         $wunit = 'mph';
44     }
45     if ( trim((string)$res->weather['value']) == trim((string)$res->clouds['name']) ) {
46         $desc = (string)$res->clouds['name'];
47     } else {
48         $desc = (string)$res->weather['value'].', '.(string)$res->clouds['name'];
49     }
50     $r = array(
51         'city'=> (string) $res->city['name'][0],
52         'country' => (string) $res->city->country[0],
53         'lat' => (string) $res->city->coord['lat'],
54         'lon' => (string) $res->city->coord['lon'],
55         'temperature' => (string) $res->temperature['value'][0].$tunit,
56         'pressure' => (string) $res->pressure['value'].(string)$res->pressure['unit'],
57         'humidity' => (string) $res->humidity['value'].(string)$res->humidity['unit'],
58         'descripion' => $desc,
59         'wind' => (string)$res->wind->speed['name'].' ('.(string)$res->wind->speed['value'].$wunit.')',
60         'update' => (string)$res->lastupdate['value'],
61         'icon' => (string)$res->weather['icon']
62     );
63     PConfig::set(local_user(), 'curweather', 'last', $now->getTimestamp());
64     Cache::set('curweather'.md5($url), serialize($r), CACHE_HOUR);
65     return $r;
66 }
67
68 function curweather_install() {
69         register_hook('network_mod_init', 'addon/curweather/curweather.php', 'curweather_network_mod_init');
70         register_hook('plugin_settings', 'addon/curweather/curweather.php', 'curweather_plugin_settings');
71         register_hook('plugin_settings_post', 'addon/curweather/curweather.php', 'curweather_plugin_settings_post');
72 }
73
74 function curweather_uninstall() {
75         unregister_hook('network_mod_init', 'addon/curweather/curweather.php', 'curweather_network_mod_init');
76         unregister_hook('plugin_settings', 'addon/curweather/curweather.php', 'curweather_plugin_settings');
77         unregister_hook('plugin_settings_post', 'addon/curweather/curweather.php', 'curweather_plugin_settings_post');
78 }
79
80 function curweather_network_mod_init(&$fk_app,&$b) {
81
82     if(! intval(PConfig::get(local_user(),'curweather','curweather_enable')))
83         return;
84
85     $fk_app->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $fk_app->get_baseurl() . '/addon/curweather/curweather.css' . '" media="all" />' . "\r\n";
86
87     // $rpt value is needed for location
88     // $lang will be taken from the browser session to honour user settings
89     // TODO $lang does not work if the default settings are used
90     //      and not all response strings are translated
91     // $units can be set in the settings by the user
92     // $appid is configured by the admin in the admin panel
93     // those parameters will be used to get: cloud status, temperature, preassure
94     // and relative humidity for display, also the relevent area of the map is
95     // linked from lat/log of the reply of OWMp
96     $rpt = PConfig::get(local_user(), 'curweather', 'curweather_loc');
97
98
99     //  set the language to the browsers language and use metric units
100     $lang = $_SESSION['language'];
101     $units = PConfig::get( local_user(), 'curweather', 'curweather_units');
102     $appid = Config::get('curweather','appid');
103     $cachetime = intval(Config::get('curweather','cachetime'));
104     if ($units==="")
105         $units = 'metric';
106     $ok = true;
107
108     $res = getWeather($rpt, $units, $lang, $appid, $cachetime);
109     if ($res===false)
110         $ok = false;
111
112     if ($ok) {
113         $t = get_markup_template("widget.tpl", "addon/curweather/" );
114         $curweather = replace_macros ($t, array(
115             '$title' => t("Current Weather"),
116             '$icon' => proxy_url('http://openweathermap.org/img/w/'.$res['icon'].'.png'),
117             '$city' => $res['city'],
118             '$lon' => $res['lon'],
119             '$lat' => $res['lat'],
120             '$description' => $res['descripion'],
121             '$temp' => $res['temperature'],
122             '$relhumidity' => array('caption'=>t('Relative Humidity'), 'val'=>$res['humidity']),
123             '$pressure' => array('caption'=>t('Pressure'), 'val'=>$res['pressure']),
124             '$wind' => array('caption'=>t('Wind'), 'val'=> $res['wind']),
125             '$lastupdate' => t('Last Updated').': '.$res['update'].'UTC',
126             '$databy' =>  t('Data by'),
127             '$showonmap' => t('Show on map')
128         ));
129     } else {
130         $t = get_markup_template('widget-error.tpl', 'addon/curweather/');
131         $curweather = replace_macros( $t, array(
132             '$problem' => t('There was a problem accessing the weather data. But have a look'),
133             '$rpt' => $rpt,
134             '$atOWM' => t('at OpenWeatherMap')
135         ));
136     }
137
138     $fk_app->page['aside'] = $curweather.$fk_app->page['aside'];
139
140 }
141
142
143 function curweather_plugin_settings_post($a,$post) {
144         if(! local_user() || (! x($_POST,'curweather-settings-submit')))
145                 return;
146         PConfig::set(local_user(),'curweather','curweather_loc',trim($_POST['curweather_loc']));
147         PConfig::set(local_user(),'curweather','curweather_enable',intval($_POST['curweather_enable']));
148         PConfig::set(local_user(),'curweather','curweather_units',trim($_POST['curweather_units']));
149
150         info( t('Current Weather settings updated.') . EOL);
151 }
152
153
154 function curweather_plugin_settings(&$a,&$s) {
155
156         if(! local_user())
157                 return;
158
159         /* Get the current state of our config variable */
160
161         $curweather_loc = PConfig::get(local_user(), 'curweather', 'curweather_loc');
162         $curweather_units = PConfig::get(local_user(), 'curweather', 'curweather_units');
163         $appid = Config::get('curweather','appid');
164         if ($appid=="") { 
165                 $noappidtext = t('No APPID found, please contact your admin to obtain one.');
166         } else {
167             $noappidtext = '';
168         }
169         $enable = intval(PConfig::get(local_user(),'curweather','curweather_enable'));
170         $enable_checked = (($enable) ? ' checked="checked" ' : '');
171         
172         // load template and replace the macros
173         $t = get_markup_template("settings.tpl", "addon/curweather/" );
174         $s = replace_macros ($t, array(
175                 '$submit' => t('Save Settings'),            
176                 '$header' => t('Current Weather').' '.t('Settings'),
177                 '$noappidtext' => $noappidtext,
178                 '$info' => t('Enter either the name of your location or the zip code.'),
179                 '$curweather_loc' => array( 'curweather_loc', t('Your Location'), $curweather_loc, t('Identifier of your location (name or zip code), e.g. <em>Berlin,DE</em> or <em>14476,DE</em>.') ),
180                 '$curweather_units' => array( 'curweather_units', t('Units'), $curweather_units, t('select if the temperature should be displayed in &deg;C or &deg;F'), array('metric'=>'°C', 'imperial'=>'°F')),
181                 '$enabled' => array( 'curweather_enable', t('Show weather data'), $enable, '')
182             ));
183         return;
184
185 }
186 // Config stuff for the admin panel to let the admin of the node set a APPID
187 // for accessing the API of openweathermap
188 function curweather_plugin_admin_post (&$a) {
189         if(! is_site_admin())
190             return;
191         if ($_POST['curweather-submit']) {
192             Config::set('curweather','appid',trim($_POST['appid']));
193             Config::set('curweather','cachetime',trim($_POST['cachetime']));
194             info( t('Curweather settings saved.'.EOL));
195         }
196 }
197 function curweather_plugin_admin (&$a, &$o) {
198     if(! is_site_admin())
199             return;
200     $appid = Config::get('curweather','appid');
201     $cachetime = Config::get('curweather','cachetime');
202     $t = get_markup_template("admin.tpl", "addon/curweather/" );
203     $o = replace_macros ($t, array(
204         '$submit' => t('Save Settings'),
205         '$cachetime' => array('cachetime', t('Caching Interval'), $cachetime, t('For how long should the weather data be cached? Choose according your OpenWeatherMap account type.'), array('0'=>t('no cache'), '300'=>'5 '.t('minutes'), '900'=>'15 '.t('minutes'), '1800'=>'30 '.t('minutes'), '3600'=>'60 '.t('minutes'))),
206         '$appid' => array('appid', t('Your APPID'), $appid, t('Your API key provided by OpenWeatherMap'))
207     ));
208 }