924587d8ab9da210f814e004d718732e79837c50
[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         begin_transaction(__FUNCTION__, func_get_args());
67
68         $date = date2sql($date_);
69                 
70         $sql = "UPDATE ".TB_PREF."exchange_rates SET rate_buy=$buy_rate, rate_sell=".db_escape($sell_rate)
71         ." WHERE curr_code=".db_escape($curr_code)." AND date_='$date'";
72                                 
73         db_query($sql, "could not add exchange rate for $curr_code");
74
75         commit_transaction();
76 }
77
78 //---------------------------------------------------------------------------------------------
79
80 function add_exchange_rate($curr_code, $date_, $buy_rate, $sell_rate)
81 {
82         if (is_company_currency($curr_code))
83                 display_db_error("Exchange rates cannot be set for company currency", "", true);
84
85         begin_transaction(__FUNCTION__, func_get_args());
86         $date = date2sql($date_);
87                 
88         $sql = "INSERT INTO ".TB_PREF."exchange_rates (curr_code, date_, rate_buy, rate_sell)
89                 VALUES (".db_escape($curr_code).", '$date', ".db_escape($buy_rate)
90                 .", ".db_escape($sell_rate).")";
91         db_query($sql, "could not add exchange rate for $curr_code");
92         commit_transaction();
93 }
94
95 //---------------------------------------------------------------------------------------------
96
97 function add_new_exchange_rate($curr_code, $date_, $ex_rate)
98 {
99         if (is_company_currency($curr_code) || !$ex_rate)
100                 return;
101
102         if (!get_date_exchange_rate($curr_code, $date_))
103                 add_exchange_rate($curr_code, $date_, $ex_rate, $ex_rate);
104 }
105
106 //---------------------------------------------------------------------------------------------
107
108 function delete_exchange_rate($rate_id)
109 {
110         begin_transaction(__FUNCTION__, func_get_args());
111
112         $sql = "DELETE FROM ".TB_PREF."exchange_rates WHERE id=".db_escape($rate_id);
113         db_query($sql, "could not delete exchange rate $rate_id");
114
115         commit_transaction();
116 }
117
118 //-----------------------------------------------------------------------------
119 //      Retrieve exchange rate as of date $date from external source (usually inet)
120 //
121 //      Exchange rate for currency revaluation purposes is defined in FA as home_currency/curr_b ratio i.e.
122 //
123 //      amount [home] = amount [curr] * ex_rate
124 //
125 function retrieve_exrate($curr_b, $date)
126 {
127         global $SysPrefs;
128
129         $xchg_rate_provider = ((isset($SysPrefs->xr_providers) && isset($SysPrefs->dflt_xr_provider)) 
130                 ? $SysPrefs->xr_providers[$SysPrefs->dflt_xr_provider] : 'ECB');
131
132         $rate = hook_retrieve_exrate($curr_b, $date);
133         if (is_numeric($rate))
134                 return $rate;
135         return get_extern_rate($curr_b, $xchg_rate_provider, $date);
136 }
137 //-----------------------------------------------------------------------------
138
139 function get_extern_rate($curr_b, $provider = 'ECB', $date) 
140 {
141         global  $path_to_root;
142
143         if ($date != Today())   // no historical rates available
144                 return 0;
145
146         $contents = '';
147         $proto = 'http://';
148         $curr_a = get_company_pref('curr_default');
149         if ($provider == 'ECB')
150     {
151         $filename = "/stats/eurofxref/eurofxref-daily.xml";
152         $site = "www.ecb.europa.eu";
153         $proto = 'https://';
154         $site_ip="172.230.157.137";
155         $contents=file_get_contents($proto.$site.$filename);
156     }
157         elseif ($provider == 'YAHOO')
158         {
159                 $filename = "/d/quotes.csv?s={$curr_a}{$curr_b}=X&f=sl1d1t1ba&e=.csv"; // new URL's for YAHOO
160                 $site = "download.finance.yahoo.com";
161                 $site_ip="203.84.220.151";
162         }
163         elseif ($provider == 'GOOGLE')
164         {
165                 $filename = "/search?q={$curr_b}+to+{$curr_a}";
166                 $site = "https://www.google.com";
167                 $contents = file_get_contents($site.$filename);
168         }
169         elseif ($provider == 'BLOOMBERG')
170         {
171                 $filename = "/quote/{$curr_b}{$curr_a}:CUR";
172                 $site = "www.bloomberg.com";
173                 $proto = 'https://';
174                 $contents=file_get_contents($proto.$site.$filename);
175         }
176         elseif ($provider == 'EXCHANGE-RATES.ORG')
177         {
178                 $filename = "/converter/{$curr_b}/{$curr_a}/1";
179                 $site = "exchange-rates.org";
180                 $proto = 'https://';
181                 $contents=file_get_contents($proto.$site.$filename);
182         }
183         if (empty($contents)) {
184                 if (function_exists('curl_init'))
185                 {       // first check with curl as we can set short timeout;
186                         $retry = 1;
187                         do {
188                         $ch = curl_init();
189                         curl_setopt ($ch, CURLOPT_URL, $proto.$site.$filename);
190                         curl_setopt ($ch, CURLOPT_COOKIEJAR, VARLIB_PATH."/cookie.txt");
191                         curl_setopt ($ch, CURLOPT_HEADER, 0);
192                         curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
193                         // prevent warning while safe_mode/open_basedir on (redirection doesn't occur at least on ECB page)
194                                 if (!ini_get('safe_mode') && !ini_get('open_basedir'))
195                                 curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
196                         curl_setopt ($ch, CURLOPT_TIMEOUT, 3);
197                         $contents = curl_exec ($ch);
198                         curl_close($ch);
199                                 // due to resolver bug in some curl versions (e.g. 7.15.5) 
200                                 // try again for constant IP.
201                                 if (isset($site_ip))
202                                         $site=$site_ip;
203                         } while( ($contents == '') && $retry--);
204                 } else {
205                         $contents = url_get_contents($proto.$site.$filename);
206                 }
207         }
208         $val = '';
209         if ($provider == 'ECB')
210         {
211                 $contents = str_replace ("<Cube currency='USD'", " <Cube currency='EUR' rate='1'/> <Cube currency='USD'", $contents);
212                 $from_mask = "|<Cube\s*currency=\'" . $curr_a . "\'\s*rate=\'([\d.,]*)\'\s*/>|i";
213                 preg_match ( $from_mask, $contents, $out );
214                 $val_a = isset($out[1]) ? $out[1] : 0;
215                 $val_a = str_replace ( ',', '', $val_a );
216                 $to_mask = "|<Cube\s*currency=\'" . $curr_b . "\'\s*rate=\'([\d.,]*)\'\s*/>|i";
217                 preg_match ( $to_mask, $contents, $out );
218                 $val_b = isset($out[1]) ? $out[1] : 0;
219                 $val_b = str_replace ( ',', '', $val_b );
220                 if ($val_b) 
221                 {
222                         $val = $val_a / $val_b;
223                 } 
224                 else 
225                 {
226                         $val = 0;
227                 }
228         }
229         elseif ($provider == 'YAHOO')
230         {
231                 $array = explode(',',$contents); // New operations for YAHOO. Safer.
232                 $val = $array[1];
233                 if ($val != 0)
234                         $val = 1 / $val;
235         }
236         elseif ($provider == 'GOOGLE')
237         {
238                 $data = preg_split('/\D\s(.*?)\s=\s/', $contents);
239                 $array = explode(" ", $data[1]);
240                 $exRate = $array[0];
241
242                 $val = str_replace (',', '', $exRate);
243     }
244         elseif ($provider == 'BLOOMBERG')
245         {
246                 $val = getInnerStr($contents, ',"price":', ',"');
247     }    
248     elseif ($provider == 'EXCHANGE-RATES.ORG')
249         {
250                 $val = getInnerStr($contents, '<span id="ctl00_M_lblToAmount">', '<');
251                 $val = str_replace (',', '', $val);
252     }
253         return $val;
254 }  /* end function get_extern_rate */
255
256 //-----------------------------------------------------------------------------
257
258 function get_sql_for_exchange_rates($curr)
259 {
260         $sql = "SELECT date_, rate_buy, id
261                 FROM ".TB_PREF."exchange_rates "
262                 ."WHERE curr_code=".db_escape($curr)."
263                  ORDER BY date_ DESC";
264         return $sql;     
265 }
266
267 function getInnerStr($str, $start, $end) 
268 {
269         // $start must be the first occurrence
270         // $start must not be part of $end
271         $val = '';
272         $val = strstr($str, $start);
273         $val = trim($val);
274         $val = substr($val, strlen($start));
275         $val = strtok($val, $end);
276         return trim($val);
277 }