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