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