f067254c6433fe20dd93f5b5f2c4df44211b84bb
[fa-stable.git] / gl / includes / db / gl_db_rates.inc
1 <?php
2 /**********************************************************************
3     Copyright (C) FrontAccounting, LLC.
4         Released under the terms of the GNU General Public License, GPL, 
5         as published by the Free Software Foundation, either version 3 
6         of the License, or (at your option) any later version.
7     This program is distributed in the hope that it will be useful,
8     but WITHOUT ANY WARRANTY; without even the implied warranty of
9     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
10     See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
11 ***********************************************************************/
12 include_once($path_to_root . "/includes/remote_url.inc");
13 //---------------------------------------------------------------------------------------------
14 function get_exchange_rate($rate_id)
15 {
16         $sql = "SELECT * FROM ".TB_PREF."exchange_rates WHERE id=".db_escape($rate_id);
17         $result = db_query($sql, "could not get exchange rate for $rate_id");
18
19         return db_fetch($result);
20 }
21
22 // Retrieves buy exchange rate for given currency/date, zero if no result
23 function get_date_exchange_rate($curr_code, $date_)
24 {
25         $date = date2sql($date_);
26         $sql = "SELECT rate_buy
27                         FROM ".TB_PREF."exchange_rates
28                         WHERE curr_code=".db_escape($curr_code)
29                                 ." AND date_='$date'";
30         $result = db_query($sql, "could not get exchange rate for $curr_code - $date_");
31
32         if(db_num_rows($result) == 0) 
33                 return 0;
34         $row = db_fetch($result);
35                 return $row[0];
36 }
37
38 /*
39         Return last exchange rate of $currency not later than $date.
40 */
41 function get_last_exchange_rate($curr_code, $date_)
42 {
43         $date = date2sql($date_);
44
45         $sql = "SELECT rate_buy, max(date_) as date_
46                         FROM ".TB_PREF."exchange_rates
47                         WHERE curr_code = ".db_escape($curr_code)."
48                                 AND date_ <= '$date' GROUP BY rate_buy ORDER BY date_ Desc LIMIT 1";
49
50         $result = db_query($sql, "could not query exchange rates");
51
52
53         if (db_num_rows($result) == 0)
54                 return false;
55
56         return db_fetch_assoc($result);
57 }
58
59 //---------------------------------------------------------------------------------------------
60
61 function update_exchange_rate($curr_code, $date_, $buy_rate, $sell_rate)
62 {
63         if (is_company_currency($curr_code))
64                 display_db_error("Exchange rates cannot be set for company currency", "", true);
65                         
66         $date = date2sql($date_);
67                 
68         $sql = "UPDATE ".TB_PREF."exchange_rates SET rate_buy=$buy_rate, rate_sell=".db_escape($sell_rate)
69         ." WHERE curr_code=".db_escape($curr_code)." AND date_='$date'";
70                                 
71         db_query($sql, "could not add exchange rate for $curr_code");
72 }
73
74 //---------------------------------------------------------------------------------------------
75
76 function add_exchange_rate($curr_code, $date_, $buy_rate, $sell_rate)
77 {
78         if (is_company_currency($curr_code))
79                 display_db_error("Exchange rates cannot be set for company currency", "", true);
80
81         $date = date2sql($date_);
82                 
83         $sql = "INSERT INTO ".TB_PREF."exchange_rates (curr_code, date_, rate_buy, rate_sell)
84                 VALUES (".db_escape($curr_code).", '$date', ".db_escape($buy_rate)
85                 .", ".db_escape($sell_rate).")";
86         db_query($sql, "could not add exchange rate for $curr_code");
87 }
88
89 //---------------------------------------------------------------------------------------------
90
91 function add_new_exchange_rate($curr_code, $date_, $ex_rate)
92 {
93         if (is_company_currency($curr_code) || !$ex_rate)
94                 return;
95
96         if (!get_date_exchange_rate($curr_code, $date_))
97                 add_exchange_rate($curr_code, $date_, $ex_rate, $ex_rate);
98 }
99
100 //---------------------------------------------------------------------------------------------
101
102 function delete_exchange_rate($rate_id)
103 {
104         $sql = "DELETE FROM ".TB_PREF."exchange_rates WHERE id=".db_escape($rate_id);
105         db_query($sql, "could not delete exchange rate $rate_id");
106 }
107
108 //-----------------------------------------------------------------------------
109 //      Retrieve exchange rate as of date $date from external source (usually inet)
110 //
111 //      Exchange rate for currency revaluation purposes is defined in FA as home_currency/curr_b ratio i.e.
112 //
113 //      amount [home] = amount [curr] * ex_rate
114 //
115 function retrieve_exrate($curr_b, $date)
116 {
117         global $SysPrefs;
118
119         $xchg_rate_provider = ((isset($SysPrefs->xr_providers) && isset($SysPrefs->dflt_xr_provider)) 
120                 ? $SysPrefs->xr_providers[$SysPrefs->dflt_xr_provider] : 'ECB');
121
122         $rate = hook_retrieve_exrate($curr_b, $date);
123         if (is_numeric($rate))
124                 return $rate;
125         return get_extern_rate($curr_b, $xchg_rate_provider, $date);
126 }
127 //-----------------------------------------------------------------------------
128
129 function get_extern_rate($curr_b, $provider = 'ECB', $date) 
130 {
131         global  $path_to_root;
132
133         if ($date != Today())   // no historical rates available
134                 return 0;
135
136         $contents = '';
137         $proto = 'http://';
138         $curr_a = get_company_pref('curr_default');
139         if ($provider == 'ECB')
140     {
141         $filename = "/stats/eurofxref/eurofxref-daily.xml";
142         $site = "www.ecb.europa.eu";
143         $proto = 'https://';
144         $site_ip="172.230.157.137";
145         $contents=file_get_contents($proto.$site.$filename);
146     }
147         elseif ($provider == 'YAHOO')
148         {
149                 $filename = "/d/quotes.csv?s={$curr_a}{$curr_b}=X&f=sl1d1t1ba&e=.csv"; // new URL's for YAHOO
150                 $site = "download.finance.yahoo.com";
151                 $site_ip="203.84.220.151";
152         }
153         elseif ($provider == 'GOOGLE')
154         {
155                 $filename = "/bctzjpnsun/converter?a=1&from={$curr_a}&to={$curr_b}";
156                 $site = "finance.google.com";
157         }
158         elseif ($provider == 'BLOOMBERG')
159         {
160                 $filename = "/quote/{$curr_b}{$curr_a}:CUR";
161                 $site = "www.bloomberg.com";
162                 $proto = 'https://';
163                 $contents=file_get_contents($proto.$site.$filename);
164         }
165         elseif ($provider == 'EXCHANGE-RATES.ORG')
166         {
167                 $filename = "/converter/{$curr_b}/{$curr_a}/1";
168                 $site = "exchange-rates.org";
169                 $proto = 'https://';
170                 $contents=file_get_contents($proto.$site.$filename);
171         }
172         elseif ($provider == 'CCA')
173         {
174                 $filename = "/api/v6/convert?q={$curr_b}_{$curr_a}&compact=y&callback=sampleCallback";
175                 $site = "free.currencyconverterapi.com";
176                 $proto = 'https://';
177                 $contents=file_get_contents($proto.$site.$filename);
178         }
179         if (empty($contents)) {
180                 if (function_exists('curl_init'))
181                 {       // first check with curl as we can set short timeout;
182                         $retry = 1;
183                         do {
184                         $ch = curl_init();
185                         curl_setopt ($ch, CURLOPT_URL, $proto.$site.$filename);
186                         curl_setopt ($ch, CURLOPT_COOKIEJAR, VARLIB_PATH."/cookie.txt");
187                         curl_setopt ($ch, CURLOPT_HEADER, 0);
188                         curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
189                         // prevent warning while safe_mode/open_basedir on (redirection doesn't occur at least on ECB page)
190                                 if (!ini_get('safe_mode') && !ini_get('open_basedir'))
191                                 curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
192                         curl_setopt ($ch, CURLOPT_TIMEOUT, 3);
193                         $contents = curl_exec ($ch);
194                         curl_close($ch);
195                                 // due to resolver bug in some curl versions (e.g. 7.15.5) 
196                                 // try again for constant IP.
197                                 if (isset($site_ip))
198                                         $site=$site_ip;
199                         } while( ($contents == '') && $retry--);
200                 } else {
201                         $contents = url_get_contents($proto.$site.$filename);
202                 }
203         }
204         $val = '';
205         if ($provider == 'ECB')
206         {
207                 $contents = str_replace ("<Cube currency='USD'", " <Cube currency='EUR' rate='1'/> <Cube currency='USD'", $contents);
208                 $from_mask = "|<Cube\s*currency=\'" . $curr_a . "\'\s*rate=\'([\d.,]*)\'\s*/>|i";
209                 preg_match ( $from_mask, $contents, $out );
210                 $val_a = isset($out[1]) ? $out[1] : 0;
211                 $val_a = str_replace ( ',', '', $val_a );
212                 $to_mask = "|<Cube\s*currency=\'" . $curr_b . "\'\s*rate=\'([\d.,]*)\'\s*/>|i";
213                 preg_match ( $to_mask, $contents, $out );
214                 $val_b = isset($out[1]) ? $out[1] : 0;
215                 $val_b = str_replace ( ',', '', $val_b );
216                 if ($val_b) 
217                 {
218                         $val = $val_a / $val_b;
219                 } 
220                 else 
221                 {
222                         $val = 0;
223                 }
224         }
225         elseif ($provider == 'YAHOO')
226         {
227                 $array = explode(',',$contents); // New operations for YAHOO. Safer.
228                 $val = $array[1];
229                 if ($val != 0)
230                         $val = 1 / $val;
231         }
232         elseif ($provider == 'GOOGLE')
233         {
234                 $val = getInnerStr($contents, '<span class=bld>', ' ');
235                 if (empty($val) || $val+0 <= 0.0001) {
236                         // reverse lookup on could not convert for too small values 
237             $filename = "/bctzjpnsun/converter?a=1&from={$curr_b}&to={$curr_a}";
238             $contents = url_get_contents($proto.$site.$filename);
239             $val = getInnerStr($contents, '<span class=bld>', ' ');
240                 } else {
241                         if ($val != 0)
242                                 $val = 1 / $val;
243                 }
244     }    
245         elseif ($provider == 'BLOOMBERG')
246         {
247                 $val = getInnerStr($contents, ',"price":', ',"');
248     }    
249     elseif ($provider == 'EXCHANGE-RATES.ORG')
250         {
251                 $val = getInnerStr($contents, '<span id="ctl00_M_lblToAmount">', '<');
252     }
253     elseif ($provider == 'CCA')
254     {
255         $val = getInnerStr($contents, '"val":', '}');
256     }
257         return $val;
258 }  /* end function get_extern_rate */
259
260 //-----------------------------------------------------------------------------
261
262 function get_sql_for_exchange_rates($curr)
263 {
264         $sql = "SELECT date_, rate_buy, id
265                 FROM ".TB_PREF."exchange_rates "
266                 ."WHERE curr_code=".db_escape($curr)."
267                  ORDER BY date_ DESC";
268         return $sql;     
269 }
270
271 function getInnerStr($str, $start, $end) 
272 {
273         // $start must be the first occurrence
274         // $start must not be part of $end
275         $val = '';
276         $val = strstr($str, $start);
277         $val = trim($val);
278         $val = substr($val, strlen($start));
279         $val = strtok($val, $end);
280         return trim($val);
281 }