3 * Name: Current Weather
4 * Description: Shows current weather conditions for user's location on their network page.
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>
12 require_once('include/network.php');
13 require_once("mod/proxy.php");
14 require_once('include/text.php');
16 use Friendica\Core\Addon;
17 use Friendica\Core\Cache;
18 use Friendica\Core\Config;
19 use Friendica\Core\PConfig;
21 // get the weather data from OpenWeatherMap
22 function getWeather( $loc, $units='metric', $lang='en', $appid='', $cachetime=0) {
23 $url = "http://api.openweathermap.org/data/2.5/weather?q=".$loc."&appid=".$appid."&lang=".$lang."&units=".$units."&mode=xml";
24 $cached = Cache::get('curweather'.md5($url));
25 $now = new DateTime();
26 if (!is_null($cached)) {
27 $cdate = PConfig::get(local_user(), 'curweather', 'last');
28 $cached = unserialize($cached);
29 if ($cdate + $cachetime > $now->getTimestamp()) {
34 $res = new SimpleXMLElement(fetch_url($url));
35 } catch (Exception $e) {
36 info(t('Error fetching weather data.\nError was: '.$e->getMessage()));
39 if ((string)$res->temperature['unit']==='metric') {
46 if ( trim((string)$res->weather['value']) == trim((string)$res->clouds['name']) ) {
47 $desc = (string)$res->clouds['name'];
49 $desc = (string)$res->weather['value'].', '.(string)$res->clouds['name'];
52 'city'=> (string) $res->city['name'][0],
53 'country' => (string) $res->city->country[0],
54 'lat' => (string) $res->city->coord['lat'],
55 'lon' => (string) $res->city->coord['lon'],
56 'temperature' => (string) $res->temperature['value'][0].$tunit,
57 'pressure' => (string) $res->pressure['value'].(string)$res->pressure['unit'],
58 'humidity' => (string) $res->humidity['value'].(string)$res->humidity['unit'],
59 'descripion' => $desc,
60 'wind' => (string)$res->wind->speed['name'].' ('.(string)$res->wind->speed['value'].$wunit.')',
61 'update' => (string)$res->lastupdate['value'],
62 'icon' => (string)$res->weather['icon']
64 PConfig::set(local_user(), 'curweather', 'last', $now->getTimestamp());
65 Cache::set('curweather'.md5($url), serialize($r), CACHE_HOUR);
69 function curweather_install()
71 Addon::registerHook('network_mod_init', 'addon/curweather/curweather.php', 'curweather_network_mod_init');
72 Addon::registerHook('addon_settings', 'addon/curweather/curweather.php', 'curweather_addon_settings');
73 Addon::registerHook('addon_settings_post', 'addon/curweather/curweather.php', 'curweather_addon_settings_post');
76 function curweather_uninstall() {
77 Addon::unregisterHook('network_mod_init', 'addon/curweather/curweather.php', 'curweather_network_mod_init');
78 Addon::unregisterHook('addon_settings', 'addon/curweather/curweather.php', 'curweather_addon_settings');
79 Addon::unregisterHook('addon_settings_post', 'addon/curweather/curweather.php', 'curweather_addon_settings_post');
82 function curweather_network_mod_init(&$fk_app,&$b) {
84 if(! intval(PConfig::get(local_user(),'curweather','curweather_enable')))
87 $fk_app->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $fk_app->get_baseurl() . '/addon/curweather/curweather.css' . '" media="all" />' . "\r\n";
89 // $rpt value is needed for location
90 // $lang will be taken from the browser session to honour user settings
91 // TODO $lang does not work if the default settings are used
92 // and not all response strings are translated
93 // $units can be set in the settings by the user
94 // $appid is configured by the admin in the admin panel
95 // those parameters will be used to get: cloud status, temperature, preassure
96 // and relative humidity for display, also the relevent area of the map is
97 // linked from lat/log of the reply of OWMp
98 $rpt = PConfig::get(local_user(), 'curweather', 'curweather_loc');
101 // set the language to the browsers language and use metric units
102 $lang = $_SESSION['language'];
103 $units = PConfig::get( local_user(), 'curweather', 'curweather_units');
104 $appid = Config::get('curweather','appid');
105 $cachetime = intval(Config::get('curweather','cachetime'));
110 $res = getWeather($rpt, $units, $lang, $appid, $cachetime);
115 $t = get_markup_template("widget.tpl", "addon/curweather/" );
116 $curweather = replace_macros ($t, [
117 '$title' => t("Current Weather"),
118 '$icon' => proxy_url('http://openweathermap.org/img/w/'.$res['icon'].'.png'),
119 '$city' => $res['city'],
120 '$lon' => $res['lon'],
121 '$lat' => $res['lat'],
122 '$description' => $res['descripion'],
123 '$temp' => $res['temperature'],
124 '$relhumidity' => ['caption'=>t('Relative Humidity'), 'val'=>$res['humidity']],
125 '$pressure' => ['caption'=>t('Pressure'), 'val'=>$res['pressure']],
126 '$wind' => ['caption'=>t('Wind'), 'val'=> $res['wind']],
127 '$lastupdate' => t('Last Updated').': '.$res['update'].'UTC',
128 '$databy' => t('Data by'),
129 '$showonmap' => t('Show on map')
132 $t = get_markup_template('widget-error.tpl', 'addon/curweather/');
133 $curweather = replace_macros( $t, [
134 '$problem' => t('There was a problem accessing the weather data. But have a look'),
136 '$atOWM' => t('at OpenWeatherMap')
140 $fk_app->page['aside'] = $curweather.$fk_app->page['aside'];
145 function curweather_addon_settings_post($a,$post) {
146 if(! local_user() || (! x($_POST,'curweather-settings-submit')))
148 PConfig::set(local_user(),'curweather','curweather_loc',trim($_POST['curweather_loc']));
149 PConfig::set(local_user(),'curweather','curweather_enable',intval($_POST['curweather_enable']));
150 PConfig::set(local_user(),'curweather','curweather_units',trim($_POST['curweather_units']));
152 info( t('Current Weather settings updated.') . EOL);
156 function curweather_addon_settings(&$a,&$s) {
161 /* Get the current state of our config variable */
163 $curweather_loc = PConfig::get(local_user(), 'curweather', 'curweather_loc');
164 $curweather_units = PConfig::get(local_user(), 'curweather', 'curweather_units');
165 $appid = Config::get('curweather','appid');
167 $noappidtext = t('No APPID found, please contact your admin to obtain one.');
171 $enable = intval(PConfig::get(local_user(),'curweather','curweather_enable'));
172 $enable_checked = (($enable) ? ' checked="checked" ' : '');
174 // load template and replace the macros
175 $t = get_markup_template("settings.tpl", "addon/curweather/" );
176 $s = replace_macros ($t, [
177 '$submit' => t('Save Settings'),
178 '$header' => t('Current Weather').' '.t('Settings'),
179 '$noappidtext' => $noappidtext,
180 '$info' => t('Enter either the name of your location or the zip code.'),
181 '$curweather_loc' => [ '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>.') ],
182 '$curweather_units' => [ 'curweather_units', t('Units'), $curweather_units, t('select if the temperature should be displayed in °C or °F'), ['metric'=>'°C', 'imperial'=>'°F']],
183 '$enabled' => [ 'curweather_enable', t('Show weather data'), $enable, '']
188 // Config stuff for the admin panel to let the admin of the node set a APPID
189 // for accessing the API of openweathermap
190 function curweather_addon_admin_post (&$a) {
191 if(! is_site_admin())
193 if ($_POST['curweather-submit']) {
194 Config::set('curweather','appid',trim($_POST['appid']));
195 Config::set('curweather','cachetime',trim($_POST['cachetime']));
196 info( t('Curweather settings saved.'.EOL));
199 function curweather_addon_admin (&$a, &$o) {
200 if(! is_site_admin())
202 $appid = Config::get('curweather','appid');
203 $cachetime = Config::get('curweather','cachetime');
204 $t = get_markup_template("admin.tpl", "addon/curweather/" );
205 $o = replace_macros ($t, [
206 '$submit' => t('Save Settings'),
207 '$cachetime' => ['cachetime', t('Caching Interval'), $cachetime, t('For how long should the weather data be cached? Choose according your OpenWeatherMap account type.'), ['0'=>t('no cache'), '300'=>'5 '.t('minutes'), '900'=>'15 '.t('minutes'), '1800'=>'30 '.t('minutes'), '3600'=>'60 '.t('minutes')]],
208 '$appid' => ['appid', t('Your APPID'), $appid, t('Your API key provided by OpenWeatherMap')]