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