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