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>
13 use Friendica\Core\Cache\Duration;
14 use Friendica\Core\Hook;
15 use Friendica\Core\Renderer;
16 use Friendica\Core\Session;
18 use Friendica\Util\Proxy as ProxyUtils;
20 function curweather_install()
22 Hook::register('network_mod_init' , 'addon/curweather/curweather.php', 'curweather_network_mod_init');
23 Hook::register('addon_settings' , 'addon/curweather/curweather.php', 'curweather_addon_settings');
24 Hook::register('addon_settings_post', 'addon/curweather/curweather.php', 'curweather_addon_settings_post');
27 // get the weather data from OpenWeatherMap
28 function getWeather($loc, $units = 'metric', $lang = 'en', $appid = '', $cachetime = 0)
30 $url = "http://api.openweathermap.org/data/2.5/weather?q=" . $loc . "&appid=" . $appid . "&lang=" . $lang . "&units=" . $units . "&mode=xml";
31 $cached = DI::cache()->get('curweather'.md5($url));
32 $now = new DateTime();
34 if (!is_null($cached)) {
35 $cdate = DI::pConfig()->get(local_user(), 'curweather', 'last');
36 $cached = unserialize($cached);
38 if ($cdate + $cachetime > $now->getTimestamp()) {
44 $res = new SimpleXMLElement(DI::httpRequest()->fetch($url));
45 } catch (Exception $e) {
46 if (empty($_SESSION['curweather_notice_shown'])) {
47 notice(DI::l10n()->t('Error fetching weather data. Error was: ' . $e->getMessage()));
48 $_SESSION['curweather_notice_shown'] = true;
54 unset($_SESSION['curweather_notice_shown']);
56 if (in_array((string) $res->temperature['unit'], ['celsius', 'metric'])) {
64 if (trim((string) $res->weather['value']) == trim((string) $res->clouds['name'])) {
65 $desc = (string) $res->clouds['name'];
67 $desc = (string) $res->weather['value'] . ', ' . (string) $res->clouds['name'];
71 'city' => (string) $res->city['name'][0],
72 'country' => (string) $res->city->country[0],
73 'lat' => (string) $res->city->coord['lat'],
74 'lon' => (string) $res->city->coord['lon'],
75 'temperature' => (string) $res->temperature['value'][0].$tunit,
76 'pressure' => (string) $res->pressure['value'] . (string) $res->pressure['unit'],
77 'humidity' => (string) $res->humidity['value'] . (string) $res->humidity['unit'],
78 'descripion' => $desc,
79 'wind' => (string) $res->wind->speed['name'] . ' (' . (string) $res->wind->speed['value'] . $wunit . ')',
80 'update' => (string) $res->lastupdate['value'],
81 'icon' => (string) $res->weather['icon'],
84 DI::pConfig()->set(local_user(), 'curweather', 'last', $now->getTimestamp());
85 DI::cache()->set('curweather'.md5($url), serialize($r), Duration::HOUR);
90 function curweather_network_mod_init(App $a, &$b)
92 if (!intval(DI::pConfig()->get(local_user(), 'curweather', 'curweather_enable'))) {
96 DI::page()['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . DI::baseUrl()->get() . '/addon/curweather/curweather.css' . '" media="all" />' . "\r\n";
98 // $rpt value is needed for location
99 // $lang will be taken from the browser session to honour user settings
100 // TODO $lang does not work if the default settings are used
101 // and not all response strings are translated
102 // $units can be set in the settings by the user
103 // $appid is configured by the admin in the admin panel
104 // those parameters will be used to get: cloud status, temperature, preassure
105 // and relative humidity for display, also the relevent area of the map is
106 // linked from lat/log of the reply of OWMp
107 $rpt = DI::pConfig()->get(local_user(), 'curweather', 'curweather_loc');
109 // Set the language to the browsers language or default and use metric units
110 $lang = Session::get('language', DI::config()->get('system', 'language'));
111 $units = DI::pConfig()->get( local_user(), 'curweather', 'curweather_units');
112 $appid = DI::config()->get('curweather', 'appid');
113 $cachetime = intval(DI::config()->get('curweather', 'cachetime'));
121 $res = getWeather($rpt, $units, $lang, $appid, $cachetime);
123 if ($res === false) {
128 $t = Renderer::getMarkupTemplate("widget.tpl", "addon/curweather/" );
129 $curweather = Renderer::replaceMacros($t, [
130 '$title' => DI::l10n()->t("Current Weather"),
131 '$icon' => ProxyUtils::proxifyUrl('http://openweathermap.org/img/w/'.$res['icon'].'.png'),
132 '$city' => $res['city'],
133 '$lon' => $res['lon'],
134 '$lat' => $res['lat'],
135 '$description' => $res['descripion'],
136 '$temp' => $res['temperature'],
137 '$relhumidity' => ['caption'=>DI::l10n()->t('Relative Humidity'), 'val'=>$res['humidity']],
138 '$pressure' => ['caption'=>DI::l10n()->t('Pressure'), 'val'=>$res['pressure']],
139 '$wind' => ['caption'=>DI::l10n()->t('Wind'), 'val'=> $res['wind']],
140 '$lastupdate' => DI::l10n()->t('Last Updated').': '.$res['update'].'UTC',
141 '$databy' => DI::l10n()->t('Data by'),
142 '$showonmap' => DI::l10n()->t('Show on map')
145 $t = Renderer::getMarkupTemplate('widget-error.tpl', 'addon/curweather/');
146 $curweather = Renderer::replaceMacros( $t, [
147 '$problem' => DI::l10n()->t('There was a problem accessing the weather data. But have a look'),
149 '$atOWM' => DI::l10n()->t('at OpenWeatherMap')
153 DI::page()['aside'] = $curweather . DI::page()['aside'];
156 function curweather_addon_settings_post(App $a, $post)
158 if (!local_user() || empty($_POST['curweather-settings-submit'])) {
162 DI::pConfig()->set(local_user(), 'curweather', 'curweather_loc' , trim($_POST['curweather_loc']));
163 DI::pConfig()->set(local_user(), 'curweather', 'curweather_enable', intval($_POST['curweather_enable']));
164 DI::pConfig()->set(local_user(), 'curweather', 'curweather_units' , trim($_POST['curweather_units']));
167 function curweather_addon_settings(App $a, &$s)
173 /* Get the current state of our config variable */
174 $curweather_loc = DI::pConfig()->get(local_user(), 'curweather', 'curweather_loc');
175 $curweather_units = DI::pConfig()->get(local_user(), 'curweather', 'curweather_units');
176 $appid = DI::config()->get('curweather', 'appid');
179 $noappidtext = DI::l10n()->t('No APPID found, please contact your admin to obtain one.');
184 $enable = intval(DI::pConfig()->get(local_user(), 'curweather', 'curweather_enable'));
185 $enable_checked = (($enable) ? ' checked="checked" ' : '');
187 // load template and replace the macros
188 $t = Renderer::getMarkupTemplate("settings.tpl", "addon/curweather/" );
190 $s = Renderer::replaceMacros($t, [
191 '$submit' => DI::l10n()->t('Save Settings'),
192 '$header' => DI::l10n()->t('Current Weather').' '.DI::l10n()->t('Settings'),
193 '$noappidtext' => $noappidtext,
194 '$info' => DI::l10n()->t('Enter either the name of your location or the zip code.'),
195 '$curweather_loc' => [ 'curweather_loc', DI::l10n()->t('Your Location'), $curweather_loc, DI::l10n()->t('Identifier of your location (name or zip code), e.g. <em>Berlin,DE</em> or <em>14476,DE</em>.') ],
196 '$curweather_units' => [ 'curweather_units', DI::l10n()->t('Units'), $curweather_units, DI::l10n()->t('select if the temperature should be displayed in °C or °F'), ['metric'=>'°C', 'imperial'=>'°F']],
197 '$enabled' => [ 'curweather_enable', DI::l10n()->t('Show weather data'), $enable, '']
203 // Config stuff for the admin panel to let the admin of the node set a APPID
204 // for accessing the API of openweathermap
205 function curweather_addon_admin_post(App $a)
207 if (!is_site_admin()) {
211 if (!empty($_POST['curweather-submit'])) {
212 DI::config()->set('curweather', 'appid', trim($_POST['appid']));
213 DI::config()->set('curweather', 'cachetime', trim($_POST['cachetime']));
217 function curweather_addon_admin(App $a, &$o)
219 if (!is_site_admin()) {
223 $appid = DI::config()->get('curweather', 'appid');
224 $cachetime = DI::config()->get('curweather', 'cachetime');
226 $t = Renderer::getMarkupTemplate("admin.tpl", "addon/curweather/" );
228 $o = Renderer::replaceMacros($t, [
229 '$submit' => DI::l10n()->t('Save Settings'),
232 DI::l10n()->t('Caching Interval'),
234 DI::l10n()->t('For how long should the weather data be cached? Choose according your OpenWeatherMap account type.'), [
235 '0' => DI::l10n()->t('no cache'),
236 '300' => '5 ' . DI::l10n()->t('minutes'),
237 '900' => '15 ' . DI::l10n()->t('minutes'),
238 '1800' => '30 ' . DI::l10n()->t('minutes'),
239 '3600' => '60 ' . DI::l10n()->t('minutes')
242 '$appid' => ['appid', DI::l10n()->t('Your APPID'), $appid, DI::l10n()->t('Your API key provided by OpenWeatherMap')]