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