]> git.mxchange.org Git - friendica-addons.git/blob - curweather/curweather.php
move widget HTML into smarty3 template and update styling
[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 use Cmfcmf\OpenWeatherMap;
12 use Cmfcmf\OpenWeatherMap\AbstractCache;
13 use Cmfcmf\OpenWeatherMap\Exception as OWMException;
14
15 // Must point to composer's autoload file.
16 require('vendor/autoload.php');
17
18 function curweather_install() {
19         register_hook('network_mod_init', 'addon/curweather/curweather.php', 'curweather_network_mod_init');
20         register_hook('plugin_settings', 'addon/curweather/curweather.php', 'curweather_plugin_settings');
21         register_hook('plugin_settings_post', 'addon/curweather/curweather.php', 'curweather_plugin_settings_post');
22
23 }
24
25 function curweather_uninstall() {
26         unregister_hook('network_mod_init', 'addon/curweather/curweather.php', 'curweather_network_mod_init');
27         unregister_hook('plugin_settings', 'addon/curweather/curweather.php', 'curweather_plugin_settings');
28         unregister_hook('plugin_settings_post', 'addon/curweather/curweather.php', 'curweather_plugin_settings_post');
29
30 }
31
32 //  The caching mechanism is taken from the cache example of the
33 //  OpenWeatherMap-PHP-API library and a bit customized to allow admins to set
34 //  the caching time depending on the plans they got from openweathermap.org
35 //  and the usage of the friendica temppath
36
37 class CWCache extends AbstractCache
38 {
39     private function urlToPath($url)
40     {
41         //  take friendicas tmp directory as base for the cache
42         $tmp = get_config('system','temppath');
43         $dir = $tmp . DIRECTORY_SEPARATOR . "OpenWeatherMapPHPAPI";
44         if (!is_dir($dir)) {
45             mkdir($dir);
46         }
47
48         $path = $dir . DIRECTORY_SEPARATOR . md5($url);
49         return $path;
50     }
51
52     /**
53      * @inheritdoc
54      */
55     public function isCached($url)
56     {
57         $path = $this->urlToPath($url);
58         if (!file_exists($path) || filectime($path) + $this->seconds < time()) {
59             return false;
60         }
61         return true;
62     }
63     /**
64      * @inheritdoc
65      */
66     public function getCached($url)
67     {
68         return file_get_contents($this->urlToPath($url));
69     }
70     /**
71      * @inheritdoc
72      */
73     public function setCached($url, $content)
74     {
75         file_put_contents($this->urlToPath($url), $content);
76     }
77 }
78
79
80 function curweather_network_mod_init(&$fk_app,&$b) {
81
82     if(! intval(get_pconfig(local_user(),'curweather','curweather_enable')))
83         return;
84
85     $fk_app->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $fk_app->get_baseurl() . '/addon/curweather/curweather.css' . '" media="all" />' . "\r\n";
86
87     // the OpenWeatherMap-PHP-APIlib does all the work here
88     // the $rpt value is needed for location
89     // $lang will be taken from the browser session to honour user settings
90     // $units can be set in the settings by the user
91     // $appid is configured by the admin in the admin panel
92     // those parameters will be used to get: cloud status, temperature, preassure
93     // and relative humidity for display, also the relevent area of the map is
94     // linked from lat/log of the reply of OWMp
95     $rpt = get_pconfig(local_user(), 'curweather', 'curweather_loc');
96
97
98     //  set the language to the browsers language and use metric units
99     $lang = $_SESSION['language'];
100     $units = get_pconfig( local_user(), 'curweather', 'curweather_units');
101     $appid = get_config('curweather','appid');
102     $cachetime = intval(get_config('curweather','cachetime'));
103     if ($units==="")
104         $units = 'metric';
105     // Get OpenWeatherMap object. Don't use caching (take a look into
106     // Example_Cache.php to see how it works).
107     //$owm = new OpenWeatherMap();
108     $owm = new OpenWeatherMap(null, new CWCache(), $cachetime);
109     
110     try {
111         $weather = $owm->getWeather($rpt, $units, $lang, $appid);
112         $temp = $weather->temperature->getValue();
113         if ( $units === 'metric') {
114             $temp .= '°C';
115         } else {
116             $temp .= '°F';
117         };
118         $rhumid = $weather->humidity;
119         $pressure = $weather->pressure;
120         $wind = $weather->wind->speed->getDescription().', '.$weather->wind->speed . " " . $weather->wind->direction;
121         $description = $weather->clouds->getDescription();
122         $city = array(
123             'name'=>$weather->city->name,
124             'lon' =>$weather->city->lon,
125             'lat' =>$weather->city->lat
126         );
127     } catch(OWMException $e) {
128         info ( 'OpenWeatherMap exception: ' . $e->getMessage() . ' (Code ' . $e->getCode() . ').');
129     } catch(\Exception $e) {
130         info ('General exception: ' . $e->getMessage() . ' (Code ' . $e->getCode() . ').');
131     }
132
133     $t = get_markup_template("widget.tpl", "addon/curweather/" );
134     $curweather = replace_macros ($t, array(
135         '$title' => t("Current Weather"),
136         '$city' => $city,
137         '$description' => $description,
138         '$temp' => $temp,
139         '$relhumidity' => array('caption'=>t('Relative Humidity'), 'val'=>$rhumid),
140         '$pressure' => array('caption'=>t('Pressure'), 'val'=>$pressure),
141         '$wind' => array('caption'=>t('Wind'), 'val'=> $wind),
142         '$databy' =>  t('Data by'),
143         '$showonmap' => t('Show on map')
144     ));
145
146     $fk_app->page['aside'] = $curweather.$fk_app->page['aside'];
147
148 }
149
150
151 function curweather_plugin_settings_post($a,$post) {
152         if(! local_user() || (! x($_POST,'curweather-settings-submit')))
153                 return;
154         set_pconfig(local_user(),'curweather','curweather_loc',trim($_POST['curweather_loc']));
155         set_pconfig(local_user(),'curweather','curweather_enable',intval($_POST['curweather_enable']));
156         set_pconfig(local_user(),'curweather','curweather_units',trim($_POST['curweather_units']));
157
158         info( t('Current Weather settings updated.') . EOL);
159 }
160
161
162 function curweather_plugin_settings(&$a,&$s) {
163
164         if(! local_user())
165                 return;
166
167         /* Get the current state of our config variable */
168
169         $curweather_loc = get_pconfig(local_user(), 'curweather', 'curweather_loc');
170         $curweather_units = get_pconfig(local_user(), 'curweather', 'curweather_units');
171         $appid = get_config('curweather','appid');
172         if ($appid=="") { 
173                 $noappidtext = t('No APPID found, please contact your admin to optain one.');
174         } else {
175             $noappidtext = '';
176         }
177         $enable = intval(get_pconfig(local_user(),'curweather','curweather_enable'));
178         $enable_checked = (($enable) ? ' checked="checked" ' : '');
179         
180         // load template and replace the macros
181         $t = get_markup_template("settings.tpl", "addon/curweather/" );
182         $s = replace_macros ($t, array(
183                 '$submit' => t('Save Settings'),            
184                 '$header' => t('Current Weather').' '.t('Settings'),
185                 '$noappidtext' => $noappidtext,
186                 '$info' => t('Enter either the name of your location or the zip code.'),
187                 '$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>.') ),
188                 '$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')),
189                 '$enabled' => array( 'curweather_enable', t('Show weather data'), $enable, '')
190             ));
191         return;
192
193 }
194 // Config stuff for the admin panel to let the admin of the node set a APPID
195 // for accessing the API of openweathermap
196 function curweather_plugin_admin_post (&$a) {
197         if(! is_site_admin())
198             return;
199         if ($_POST['curweather-submit']) {
200             set_config('curweather','appid',trim($_POST['appid']));
201             set_config('curweather','cachetime',trim($_POST['cachetime']));
202             info( t('Curweather settings saved.'.EOL));
203         }
204 }
205 function curweather_plugin_admin (&$a, &$o) {
206     if(! is_site_admin())
207             return;
208     $appid = get_config('curweather','appid');
209     $cachetime = get_config('curweather','cachetime');
210     $t = get_markup_template("admin.tpl", "addon/curweather/" );
211     $o = replace_macros ($t, array(
212         '$submit' => t('Save Settings'),
213         '$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'))),
214         '$appid' => array('appid', t('Your APPID'), $appid, t('Your API key provided by OpenWeatherMap'))
215     ));
216 }