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