d9a1d20299a45abce55c87dd56b01b2c68d21caf
[friendica-addons.git/.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.2
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 use Friendica\App;
13 use Friendica\Core\Cache\Duration;
14 use Friendica\Core\Hook;
15 use Friendica\Core\Renderer;
16 use Friendica\Core\Session;
17 use Friendica\DI;
18 use Friendica\Util\Network;
19 use Friendica\Util\Proxy as ProxyUtils;
20
21 function curweather_install()
22 {
23         Hook::register('network_mod_init'   , 'addon/curweather/curweather.php', 'curweather_network_mod_init');
24         Hook::register('addon_settings'     , 'addon/curweather/curweather.php', 'curweather_addon_settings');
25         Hook::register('addon_settings_post', 'addon/curweather/curweather.php', 'curweather_addon_settings_post');
26 }
27
28 function curweather_uninstall()
29 {
30         Hook::unregister('network_mod_init'   , 'addon/curweather/curweather.php', 'curweather_network_mod_init');
31         Hook::unregister('addon_settings'     , 'addon/curweather/curweather.php', 'curweather_addon_settings');
32         Hook::unregister('addon_settings_post', 'addon/curweather/curweather.php', 'curweather_addon_settings_post');
33 }
34
35 //  get the weather data from OpenWeatherMap
36 function getWeather($loc, $units = 'metric', $lang = 'en', $appid = '', $cachetime = 0)
37 {
38         $url = "http://api.openweathermap.org/data/2.5/weather?q=" . $loc . "&appid=" . $appid . "&lang=" . $lang . "&units=" . $units . "&mode=xml";
39         $cached = DI::cache()->get('curweather'.md5($url));
40         $now = new DateTime();
41
42         if (!is_null($cached)) {
43                 $cdate = DI::pConfig()->get(local_user(), 'curweather', 'last');
44                 $cached = unserialize($cached);
45
46                 if ($cdate + $cachetime > $now->getTimestamp()) {
47                         return $cached;
48                 }
49         }
50
51         try {
52                 $res = new SimpleXMLElement(Network::fetchUrl($url));
53         } catch (Exception $e) {
54                 if (empty($_SESSION['curweather_notice_shown'])) {
55                         notice(DI::l10n()->t('Error fetching weather data. Error was: '.$e->getMessage()));
56                         $_SESSION['curweather_notice_shown'] = true;
57                 }
58
59                 return false;
60         }
61
62         unset($_SESSION['curweather_notice_shown']);
63
64         if (in_array((string) $res->temperature['unit'], ['celsius', 'metric'])) {
65                 $tunit = '°C';
66                 $wunit = 'm/s';
67         } else {
68                 $tunit = '°F';
69                 $wunit = 'mph';
70         }
71
72         if (trim((string) $res->weather['value']) == trim((string) $res->clouds['name'])) {
73                 $desc = (string) $res->clouds['name'];
74         } else {
75                 $desc = (string) $res->weather['value'] . ', ' . (string) $res->clouds['name'];
76         }
77
78         $r = [
79                 'city'        => (string) $res->city['name'][0],
80                 'country'     => (string) $res->city->country[0],
81                 'lat'         => (string) $res->city->coord['lat'],
82                 'lon'         => (string) $res->city->coord['lon'],
83                 'temperature' => (string) $res->temperature['value'][0].$tunit,
84                 'pressure'    => (string) $res->pressure['value'] . (string) $res->pressure['unit'],
85                 'humidity'    => (string) $res->humidity['value'] . (string) $res->humidity['unit'],
86                 'descripion'  => $desc,
87                 'wind'        => (string) $res->wind->speed['name'] . ' (' . (string) $res->wind->speed['value'] . $wunit . ')',
88                 'update'      => (string) $res->lastupdate['value'],
89                 'icon'        => (string) $res->weather['icon'],
90         ];
91
92         DI::pConfig()->set(local_user(), 'curweather', 'last', $now->getTimestamp());
93         DI::cache()->set('curweather'.md5($url), serialize($r), Duration::HOUR);
94
95         return $r;
96 }
97
98 function curweather_network_mod_init(App $a, &$b)
99 {
100         if (!intval(DI::pConfig()->get(local_user(), 'curweather', 'curweather_enable'))) {
101                 return;
102         }
103
104         DI::page()['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . DI::baseUrl()->get() . '/addon/curweather/curweather.css' . '" media="all" />' . "\r\n";
105
106         // $rpt value is needed for location
107         // $lang will be taken from the browser session to honour user settings
108         // TODO $lang does not work if the default settings are used
109         //      and not all response strings are translated
110         // $units can be set in the settings by the user
111         // $appid is configured by the admin in the admin panel
112         // those parameters will be used to get: cloud status, temperature, preassure
113         // and relative humidity for display, also the relevent area of the map is
114         // linked from lat/log of the reply of OWMp
115         $rpt = DI::pConfig()->get(local_user(), 'curweather', 'curweather_loc');
116
117         // Set the language to the browsers language or default and use metric units
118         $lang = Session::get('language', DI::config()->get('system', 'language'));
119         $units = DI::pConfig()->get( local_user(), 'curweather', 'curweather_units');
120         $appid = DI::config()->get('curweather', 'appid');
121         $cachetime = intval(DI::config()->get('curweather', 'cachetime'));
122
123         if ($units === "") {
124                 $units = 'metric';
125         }
126
127         $ok = true;
128
129         $res = getWeather($rpt, $units, $lang, $appid, $cachetime);
130
131         if ($res === false) {
132                 $ok = false;
133         }
134
135         if ($ok) {
136                 $t = Renderer::getMarkupTemplate("widget.tpl", "addon/curweather/" );
137                 $curweather = Renderer::replaceMacros($t, [
138                         '$title' => DI::l10n()->t("Current Weather"),
139                         '$icon' => ProxyUtils::proxifyUrl('http://openweathermap.org/img/w/'.$res['icon'].'.png'),
140                         '$city' => $res['city'],
141                         '$lon' => $res['lon'],
142                         '$lat' => $res['lat'],
143                         '$description' => $res['descripion'],
144                         '$temp' => $res['temperature'],
145                         '$relhumidity' => ['caption'=>DI::l10n()->t('Relative Humidity'), 'val'=>$res['humidity']],
146                         '$pressure' => ['caption'=>DI::l10n()->t('Pressure'), 'val'=>$res['pressure']],
147                         '$wind' => ['caption'=>DI::l10n()->t('Wind'), 'val'=> $res['wind']],
148                         '$lastupdate' => DI::l10n()->t('Last Updated').': '.$res['update'].'UTC',
149                         '$databy' =>  DI::l10n()->t('Data by'),
150                         '$showonmap' => DI::l10n()->t('Show on map')
151                 ]);
152         } else {
153                 $t = Renderer::getMarkupTemplate('widget-error.tpl', 'addon/curweather/');
154                 $curweather = Renderer::replaceMacros( $t, [
155                         '$problem' => DI::l10n()->t('There was a problem accessing the weather data. But have a look'),
156                         '$rpt' => $rpt,
157                         '$atOWM' => DI::l10n()->t('at OpenWeatherMap')
158                 ]);
159         }
160
161         DI::page()['aside'] = $curweather . DI::page()['aside'];
162 }
163
164 function curweather_addon_settings_post(App $a, $post)
165 {
166         if (!local_user() || empty($_POST['curweather-settings-submit'])) {
167                 return;
168         }
169
170         DI::pConfig()->set(local_user(), 'curweather', 'curweather_loc'   , trim($_POST['curweather_loc']));
171         DI::pConfig()->set(local_user(), 'curweather', 'curweather_enable', intval($_POST['curweather_enable']));
172         DI::pConfig()->set(local_user(), 'curweather', 'curweather_units' , trim($_POST['curweather_units']));
173 }
174
175 function curweather_addon_settings(App $a, &$s)
176 {
177         if (!local_user()) {
178                 return;
179         }
180
181         /* Get the current state of our config variable */
182         $curweather_loc = DI::pConfig()->get(local_user(), 'curweather', 'curweather_loc');
183         $curweather_units = DI::pConfig()->get(local_user(), 'curweather', 'curweather_units');
184         $appid = DI::config()->get('curweather', 'appid');
185
186         if ($appid == "") {
187                 $noappidtext = DI::l10n()->t('No APPID found, please contact your admin to obtain one.');
188         } else {
189                 $noappidtext = '';
190         }
191
192         $enable = intval(DI::pConfig()->get(local_user(), 'curweather', 'curweather_enable'));
193         $enable_checked = (($enable) ? ' checked="checked" ' : '');
194         
195         // load template and replace the macros
196         $t = Renderer::getMarkupTemplate("settings.tpl", "addon/curweather/" );
197
198         $s = Renderer::replaceMacros($t, [
199                 '$submit' => DI::l10n()->t('Save Settings'),
200                 '$header' => DI::l10n()->t('Current Weather').' '.DI::l10n()->t('Settings'),
201                 '$noappidtext' => $noappidtext,
202                 '$info' => DI::l10n()->t('Enter either the name of your location or the zip code.'),
203                 '$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>.') ],
204                 '$curweather_units' => [ 'curweather_units', DI::l10n()->t('Units'), $curweather_units, DI::l10n()->t('select if the temperature should be displayed in &deg;C or &deg;F'), ['metric'=>'°C', 'imperial'=>'°F']],
205                 '$enabled' => [ 'curweather_enable', DI::l10n()->t('Show weather data'), $enable, '']
206         ]);
207
208         return;
209 }
210
211 // Config stuff for the admin panel to let the admin of the node set a APPID
212 // for accessing the API of openweathermap
213 function curweather_addon_admin_post(App $a)
214 {
215         if (!is_site_admin()) {
216                 return;
217         }
218
219         if (!empty($_POST['curweather-submit'])) {
220                 DI::config()->set('curweather', 'appid',     trim($_POST['appid']));
221                 DI::config()->set('curweather', 'cachetime', trim($_POST['cachetime']));
222         }
223 }
224
225 function curweather_addon_admin(App $a, &$o)
226 {
227         if (!is_site_admin()) {
228                 return;
229         }
230
231         $appid = DI::config()->get('curweather', 'appid');
232         $cachetime = DI::config()->get('curweather', 'cachetime');
233
234         $t = Renderer::getMarkupTemplate("admin.tpl", "addon/curweather/" );
235
236         $o = Renderer::replaceMacros($t, [
237                 '$submit' => DI::l10n()->t('Save Settings'),
238                 '$cachetime' => [
239                         'cachetime',
240                         DI::l10n()->t('Caching Interval'),
241                         $cachetime,
242                         DI::l10n()->t('For how long should the weather data be cached? Choose according your OpenWeatherMap account type.'), [
243                                 '0'    => DI::l10n()->t('no cache'),
244                                 '300'  => '5 '  . DI::l10n()->t('minutes'),
245                                 '900'  => '15 ' . DI::l10n()->t('minutes'),
246                                 '1800' => '30 ' . DI::l10n()->t('minutes'),
247                                 '3600' => '60 ' . DI::l10n()->t('minutes')
248                         ]
249                 ],
250                 '$appid' => ['appid', DI::l10n()->t('Your APPID'), $appid, DI::l10n()->t('Your API key provided by OpenWeatherMap')]
251         ]);
252 }