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\Enum\Duration;
14 use Friendica\Core\Hook;
15 use Friendica\Core\Renderer;
17 use Friendica\Util\Proxy as ProxyUtils;
19 function curweather_install()
21 Hook::register('network_mod_init' , 'addon/curweather/curweather.php', 'curweather_network_mod_init');
22 Hook::register('addon_settings' , 'addon/curweather/curweather.php', 'curweather_addon_settings');
23 Hook::register('addon_settings_post', 'addon/curweather/curweather.php', 'curweather_addon_settings_post');
26 // get the weather data from OpenWeatherMap
27 function getWeather($loc, $units = 'metric', $lang = 'en', $appid = '', $cachetime = 0)
29 $url = "http://api.openweathermap.org/data/2.5/weather?q=" . $loc . "&appid=" . $appid . "&lang=" . $lang . "&units=" . $units . "&mode=xml";
30 $cached = DI::cache()->get('curweather'.md5($url));
31 $now = new DateTime();
33 if (!is_null($cached)) {
34 $cdate = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'curweather', 'last');
35 $cached = unserialize($cached);
37 if ($cdate + $cachetime > $now->getTimestamp()) {
43 $res = new SimpleXMLElement(DI::httpClient()->fetch($url));
44 } catch (Exception $e) {
45 if (empty($_SESSION['curweather_notice_shown'])) {
46 DI::sysmsg()->addNotice(DI::l10n()->t('Error fetching weather data. Error was: ' . $e->getMessage()));
47 $_SESSION['curweather_notice_shown'] = true;
53 unset($_SESSION['curweather_notice_shown']);
55 if (in_array((string) $res->temperature['unit'], ['celsius', 'metric'])) {
63 if (trim((string) $res->weather['value']) == trim((string) $res->clouds['name'])) {
64 $desc = (string) $res->clouds['name'];
66 $desc = (string) $res->weather['value'] . ', ' . (string) $res->clouds['name'];
70 'city' => (string) $res->city['name'][0],
71 'country' => (string) $res->city->country[0],
72 'lat' => (string) $res->city->coord['lat'],
73 'lon' => (string) $res->city->coord['lon'],
74 'temperature' => (string) $res->temperature['value'][0].$tunit,
75 'pressure' => (string) $res->pressure['value'] . (string) $res->pressure['unit'],
76 'humidity' => (string) $res->humidity['value'] . (string) $res->humidity['unit'],
77 'descripion' => $desc,
78 'wind' => (string) $res->wind->speed['name'] . ' (' . (string) $res->wind->speed['value'] . $wunit . ')',
79 'update' => (string) $res->lastupdate['value'],
80 'icon' => (string) $res->weather['icon'],
83 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'curweather', 'last', $now->getTimestamp());
84 DI::cache()->set('curweather'.md5($url), serialize($r), Duration::HOUR);
89 function curweather_network_mod_init(string &$body)
91 if (!intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'curweather', 'curweather_enable'))) {
95 DI::page()['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . DI::baseUrl() . '/addon/curweather/curweather.css' . '" media="all" />' . "\r\n";
97 // $rpt value is needed for location
98 // $lang will be taken from the browser session to honour user settings
99 // TODO $lang does not work if the default settings are used
100 // and not all response strings are translated
101 // $units can be set in the settings by the user
102 // $appid is configured by the admin in the admin panel
103 // those parameters will be used to get: cloud status, temperature, preassure
104 // and relative humidity for display, also the relevent area of the map is
105 // linked from lat/log of the reply of OWMp
106 $rpt = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'curweather', 'curweather_loc');
108 // Set the language to the browsers language or default and use metric units
109 $lang = DI::session()->get('language', DI::config()->get('system', 'language'));
110 $units = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'curweather', 'curweather_units');
111 $appid = DI::config()->get('curweather', 'appid');
112 $cachetime = intval(DI::config()->get('curweather', 'cachetime'));
120 $res = getWeather($rpt, $units, $lang, $appid, $cachetime);
122 if ($res === false) {
127 $t = Renderer::getMarkupTemplate("widget.tpl", "addon/curweather/" );
128 $curweather = Renderer::replaceMacros($t, [
129 '$title' => DI::l10n()->t("Current Weather"),
130 '$icon' => ProxyUtils::proxifyUrl('http://openweathermap.org/img/w/'.$res['icon'].'.png'),
131 '$city' => $res['city'],
132 '$lon' => $res['lon'],
133 '$lat' => $res['lat'],
134 '$description' => $res['descripion'],
135 '$temp' => $res['temperature'],
136 '$relhumidity' => ['caption'=>DI::l10n()->t('Relative Humidity'), 'val'=>$res['humidity']],
137 '$pressure' => ['caption'=>DI::l10n()->t('Pressure'), 'val'=>$res['pressure']],
138 '$wind' => ['caption'=>DI::l10n()->t('Wind'), 'val'=> $res['wind']],
139 '$lastupdate' => DI::l10n()->t('Last Updated').': '.$res['update'].'UTC',
140 '$databy' => DI::l10n()->t('Data by'),
141 '$showonmap' => DI::l10n()->t('Show on map')
144 $t = Renderer::getMarkupTemplate('widget-error.tpl', 'addon/curweather/');
145 $curweather = Renderer::replaceMacros( $t, [
146 '$problem' => DI::l10n()->t('There was a problem accessing the weather data. But have a look'),
148 '$atOWM' => DI::l10n()->t('at OpenWeatherMap')
152 DI::page()['aside'] = $curweather . DI::page()['aside'];
155 function curweather_addon_settings_post($post)
157 if (!DI::userSession()->getLocalUserId() || empty($_POST['curweather-settings-submit'])) {
161 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'curweather', 'curweather_loc' , trim($_POST['curweather_loc']));
162 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'curweather', 'curweather_enable', intval($_POST['curweather_enable']));
163 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'curweather', 'curweather_units' , trim($_POST['curweather_units']));
166 function curweather_addon_settings(array &$data)
168 if (!DI::userSession()->getLocalUserId()) {
172 $curweather_loc = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'curweather', 'curweather_loc');
173 $curweather_units = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'curweather', 'curweather_units');
174 $appid = DI::config()->get('curweather', 'appid');
177 $noappidtext = DI::l10n()->t('No APPID found, please contact your admin to obtain one.');
182 $enabled = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'curweather', 'curweather_enable'));
184 $t = Renderer::getMarkupTemplate('settings.tpl', 'addon/curweather/');
185 $html = Renderer::replaceMacros($t, [
186 '$noappidtext' => $noappidtext,
187 '$info' => DI::l10n()->t('Enter either the name of your location or the zip code.'),
188 '$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>.')],
189 '$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']],
190 '$enabled' => ['curweather_enable', DI::l10n()->t('Show weather data'), $enabled, ''],
194 'addon' => 'curweather',
195 'title' => DI::l10n()->t('Current Weather Settings'),
200 // Config stuff for the admin panel to let the admin of the node set a APPID
201 // for accessing the API of openweathermap
202 function curweather_addon_admin_post()
204 if (!DI::userSession()->isSiteAdmin()) {
208 if (!empty($_POST['curweather-submit'])) {
209 DI::config()->set('curweather', 'appid', trim($_POST['appid']));
210 DI::config()->set('curweather', 'cachetime', trim($_POST['cachetime']));
214 function curweather_addon_admin(string &$o)
216 if (!DI::userSession()->isSiteAdmin()) {
220 $appid = DI::config()->get('curweather', 'appid');
221 $cachetime = DI::config()->get('curweather', 'cachetime');
223 $t = Renderer::getMarkupTemplate('admin.tpl', 'addon/curweather/' );
225 $o = Renderer::replaceMacros($t, [
226 '$submit' => DI::l10n()->t('Save Settings'),
229 DI::l10n()->t('Caching Interval'),
231 DI::l10n()->t('For how long should the weather data be cached? Choose according your OpenWeatherMap account type.'), [
232 '0' => DI::l10n()->t('no cache'),
233 '300' => '5 ' . DI::l10n()->t('minutes'),
234 '900' => '15 ' . DI::l10n()->t('minutes'),
235 '1800' => '30 ' . DI::l10n()->t('minutes'),
236 '3600' => '60 ' . DI::l10n()->t('minutes')
239 '$appid' => ['appid', DI::l10n()->t('Your APPID'), $appid, DI::l10n()->t('Your API key provided by OpenWeatherMap')]