]> git.mxchange.org Git - friendica-addons.git/blob - curweather/curweather.php
audon/audon.php aktualisiert
[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\Enum\Duration;
14 use Friendica\Core\Hook;
15 use Friendica\Core\Renderer;
16 use Friendica\DI;
17 use Friendica\Util\Proxy as ProxyUtils;
18
19 function curweather_install()
20 {
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');
24 }
25
26 //  get the weather data from OpenWeatherMap
27 function getWeather($loc, $units = 'metric', $lang = 'en', $appid = '', $cachetime = 0)
28 {
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();
32
33         if (!is_null($cached)) {
34                 $cdate = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'curweather', 'last');
35                 $cached = unserialize($cached);
36
37                 if ($cdate + $cachetime > $now->getTimestamp()) {
38                         return $cached;
39                 }
40         }
41
42         try {
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;
48                 }
49
50                 return false;
51         }
52
53         unset($_SESSION['curweather_notice_shown']);
54
55         if (in_array((string) $res->temperature['unit'], ['celsius', 'metric'])) {
56                 $tunit = '°C';
57                 $wunit = 'm/s';
58         } else {
59                 $tunit = '°F';
60                 $wunit = 'mph';
61         }
62
63         if (trim((string) $res->weather['value']) == trim((string) $res->clouds['name'])) {
64                 $desc = (string) $res->clouds['name'];
65         } else {
66                 $desc = (string) $res->weather['value'] . ', ' . (string) $res->clouds['name'];
67         }
68
69         $r = [
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'],
81         ];
82
83         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'curweather', 'last', $now->getTimestamp());
84         DI::cache()->set('curweather'.md5($url), serialize($r), Duration::HOUR);
85
86         return $r;
87 }
88
89 function curweather_network_mod_init(string &$body)
90 {
91         if (!intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'curweather', 'curweather_enable'))) {
92                 return;
93         }
94
95         DI::page()['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . DI::baseUrl() . '/addon/curweather/curweather.css' . '" media="all" />' . "\r\n";
96
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');
107
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'));
113
114         if ($units === '') {
115                 $units = 'metric';
116         }
117
118         $ok = true;
119
120         $res = getWeather($rpt, $units, $lang, $appid, $cachetime);
121
122         if ($res === false) {
123                 $ok = false;
124         }
125
126         if ($ok) {
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')
142                 ]);
143         } else {
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'),
147                         '$rpt' => $rpt,
148                         '$atOWM' => DI::l10n()->t('at OpenWeatherMap')
149                 ]);
150         }
151
152         DI::page()['aside'] = $curweather . DI::page()['aside'];
153 }
154
155 function curweather_addon_settings_post($post)
156 {
157         if (!DI::userSession()->getLocalUserId() || empty($_POST['curweather-settings-submit'])) {
158                 return;
159         }
160
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']));
164 }
165
166 function curweather_addon_settings(array &$data)
167 {
168         if (!DI::userSession()->getLocalUserId()) {
169                 return;
170         }
171
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');
175
176         if ($appid == '') {
177                 $noappidtext = DI::l10n()->t('No APPID found, please contact your admin to obtain one.');
178         } else {
179                 $noappidtext = '';
180         }
181
182         $enabled = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'curweather', 'curweather_enable'));
183
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 &deg;C or &deg;F'), ['metric' => '°C', 'imperial' => '°F']],
190                 '$enabled'          => ['curweather_enable', DI::l10n()->t('Show weather data'), $enabled, ''],
191         ]);
192
193         $data = [
194                 'addon' => 'curweather',
195                 'title' => DI::l10n()->t('Current Weather Settings'),
196                 'html'  => $html,
197         ];
198 }
199
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()
203 {
204         if (!DI::userSession()->isSiteAdmin()) {
205                 return;
206         }
207
208         if (!empty($_POST['curweather-submit'])) {
209                 DI::config()->set('curweather', 'appid',     trim($_POST['appid']));
210                 DI::config()->set('curweather', 'cachetime', trim($_POST['cachetime']));
211         }
212 }
213
214 function curweather_addon_admin(string &$o)
215 {
216         if (!DI::userSession()->isSiteAdmin()) {
217                 return;
218         }
219
220         $appid = DI::config()->get('curweather', 'appid');
221         $cachetime = DI::config()->get('curweather', 'cachetime');
222
223         $t = Renderer::getMarkupTemplate('admin.tpl', 'addon/curweather/' );
224
225         $o = Renderer::replaceMacros($t, [
226                 '$submit' => DI::l10n()->t('Save Settings'),
227                 '$cachetime' => [
228                         'cachetime',
229                         DI::l10n()->t('Caching Interval'),
230                         $cachetime,
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')
237                         ]
238                 ],
239                 '$appid' => ['appid', DI::l10n()->t('Your APPID'), $appid, DI::l10n()->t('Your API key provided by OpenWeatherMap')]
240         ]);
241 }