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