cleanup namespace usages for L10n
[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\Config;
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 = 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                         info(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         Cache::set('curweather'.md5($url), serialize($r), Cache::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', Config::get('system', 'language'));
119         $units = DI::pConfig()->get( local_user(), 'curweather', 'curweather_units');
120         $appid = Config::get('curweather', 'appid');
121         $cachetime = intval(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         info(DI::l10n()->t('Current Weather settings updated.') . EOL);
175 }
176
177 function curweather_addon_settings(App $a, &$s)
178 {
179         if (!local_user()) {
180                 return;
181         }
182
183         /* Get the current state of our config variable */
184         $curweather_loc = DI::pConfig()->get(local_user(), 'curweather', 'curweather_loc');
185         $curweather_units = DI::pConfig()->get(local_user(), 'curweather', 'curweather_units');
186         $appid = Config::get('curweather', 'appid');
187
188         if ($appid == "") {
189                 $noappidtext = DI::l10n()->t('No APPID found, please contact your admin to obtain one.');
190         } else {
191                 $noappidtext = '';
192         }
193
194         $enable = intval(DI::pConfig()->get(local_user(), 'curweather', 'curweather_enable'));
195         $enable_checked = (($enable) ? ' checked="checked" ' : '');
196         
197         // load template and replace the macros
198         $t = Renderer::getMarkupTemplate("settings.tpl", "addon/curweather/" );
199
200         $s = Renderer::replaceMacros($t, [
201                 '$submit' => DI::l10n()->t('Save Settings'),
202                 '$header' => DI::l10n()->t('Current Weather').' '.DI::l10n()->t('Settings'),
203                 '$noappidtext' => $noappidtext,
204                 '$info' => DI::l10n()->t('Enter either the name of your location or the zip code.'),
205                 '$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>.') ],
206                 '$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']],
207                 '$enabled' => [ 'curweather_enable', DI::l10n()->t('Show weather data'), $enable, '']
208         ]);
209
210         return;
211 }
212
213 // Config stuff for the admin panel to let the admin of the node set a APPID
214 // for accessing the API of openweathermap
215 function curweather_addon_admin_post(App $a)
216 {
217         if (!is_site_admin()) {
218                 return;
219         }
220
221         if (!empty($_POST['curweather-submit'])) {
222                 Config::set('curweather', 'appid',     trim($_POST['appid']));
223                 Config::set('curweather', 'cachetime', trim($_POST['cachetime']));
224
225                 info(DI::l10n()->t('Curweather settings saved.' . PHP_EOL));
226         }
227 }
228
229 function curweather_addon_admin(App $a, &$o)
230 {
231         if (!is_site_admin()) {
232                 return;
233         }
234
235         $appid = Config::get('curweather', 'appid');
236         $cachetime = Config::get('curweather', 'cachetime');
237
238         $t = Renderer::getMarkupTemplate("admin.tpl", "addon/curweather/" );
239
240         $o = Renderer::replaceMacros($t, [
241                 '$submit' => DI::l10n()->t('Save Settings'),
242                 '$cachetime' => [
243                         'cachetime',
244                         DI::l10n()->t('Caching Interval'),
245                         $cachetime,
246                         DI::l10n()->t('For how long should the weather data be cached? Choose according your OpenWeatherMap account type.'), [
247                                 '0'    => DI::l10n()->t('no cache'),
248                                 '300'  => '5 '  . DI::l10n()->t('minutes'),
249                                 '900'  => '15 ' . DI::l10n()->t('minutes'),
250                                 '1800' => '30 ' . DI::l10n()->t('minutes'),
251                                 '3600' => '60 ' . DI::l10n()->t('minutes')
252                         ]
253                 ],
254                 '$appid' => ['appid', DI::l10n()->t('Your APPID'), $appid, DI::l10n()->t('Your API key provided by OpenWeatherMap')]
255         ]);
256 }