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