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