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