Merged changes from master branch up to current state.
[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 FROM ".TB_PREF."exchange_rates WHERE curr_code=".db_escape($curr_code)
27         ." AND date_='$date'";
28         $result = db_query($sql, "could not get exchange rate for $curr_code - $date_");        
29
30         if(db_num_rows($result) == 0) 
31                 return 0;
32         $row = db_fetch($result);
33                 return $row[0];
34 }
35
36 /*
37         Return last exchange rate of $currency not later than $date.
38 */
39 function get_last_exchange_rate($curr_code, $date_)
40 {
41         $date = date2sql($date_);
42
43         $sql = "SELECT rate_buy, max(date_) as date_ FROM ".TB_PREF."exchange_rates WHERE curr_code = ".db_escape($curr_code)."
44                                 AND date_ <= '$date' GROUP BY rate_buy ORDER BY date_ Desc LIMIT 1";
45
46         $result = db_query($sql, "could not query exchange rates");
47
48
49         if (db_num_rows($result) == 0)
50                 return false;
51
52         return db_fetch_assoc($result);
53 }
54
55 //---------------------------------------------------------------------------------------------
56
57 function update_exchange_rate($curr_code, $date_, $buy_rate, $sell_rate)
58 {
59         if (is_company_currency($curr_code))
60                 display_db_error("Exchange rates cannot be set for company currency", "", true);
61                         
62         $date = date2sql($date_);
63                 
64         $sql = "UPDATE ".TB_PREF."exchange_rates SET rate_buy=$buy_rate, rate_sell=".db_escape($sell_rate)
65         ." WHERE curr_code=".db_escape($curr_code)." AND date_='$date'";
66                                 
67         db_query($sql, "could not add exchange rate for $curr_code");
68 }
69
70 //---------------------------------------------------------------------------------------------
71
72 function add_exchange_rate($curr_code, $date_, $buy_rate, $sell_rate)
73 {
74         if (is_company_currency($curr_code))
75                 display_db_error("Exchange rates cannot be set for company currency", "", true);
76
77         $date = date2sql($date_);
78                 
79         $sql = "INSERT INTO ".TB_PREF."exchange_rates (curr_code, date_, rate_buy, rate_sell)
80                 VALUES (".db_escape($curr_code).", '$date', ".db_escape($buy_rate)
81                 .", ".db_escape($sell_rate).")";
82         db_query($sql, "could not add exchange rate for $curr_code");
83 }
84
85 //---------------------------------------------------------------------------------------------
86
87 function add_new_exchange_rate($curr_code, $date_, $ex_rate)
88 {
89         if (is_company_currency($curr_code) || !$ex_rate)
90                 return;
91
92         if (!get_date_exchange_rate($curr_code, $date_))
93                 add_exchange_rate($curr_code, $date_, $ex_rate, $ex_rate);
94 }
95
96 //---------------------------------------------------------------------------------------------
97
98 function delete_exchange_rate($rate_id)
99 {
100         $sql = "DELETE FROM ".TB_PREF."exchange_rates WHERE id=".db_escape($rate_id);
101         db_query($sql, "could not delete exchange rate $rate_id");
102 }
103
104 //-----------------------------------------------------------------------------
105 //      Retrieve exchange rate as of date $date from external source (usually inet)
106 //
107 //      Exchange rate for currency revaluation purposes is defined in FA as home_currency/curr_b ratio i.e.
108 //
109 //      amount [home] = amount [curr] * ex_rate
110 //
111 function retrieve_exrate($curr_b, $date)
112 {
113         global $SysPrefs;
114
115         $xchg_rate_provider = ((isset($SysPrefs->xr_providers) && isset($SysPrefs->dflt_xr_provider)) 
116                 ? $SysPrefs->xr_providers[$SysPrefs->dflt_xr_provider] : 'ECB');
117
118         $rate = hook_retrieve_exrate($curr_b, $date);
119         if (is_numeric($rate))
120                 return $rate;
121         return get_extern_rate($curr_b, $xchg_rate_provider, $date);
122 }
123 //-----------------------------------------------------------------------------
124
125 function get_extern_rate($curr_b, $provider = 'ECB', $date) 
126 {
127         global  $path_to_root;
128
129         if ($date != Today())   // no historical rates available
130                 return 0;
131
132         $curr_a = get_company_pref('curr_default');
133         if ($provider == 'ECB')
134         {
135                 $filename = "/stats/eurofxref/eurofxref-daily.xml";
136                 $site = "www.ecb.europa.eu";
137         }
138         elseif ($provider == 'YAHOO')
139         {
140                 $filename = "/d/quotes.csv?s={$curr_a}{$curr_b}=X&f=sl1d1t1ba&e=.csv"; // new URL's for YAHOO
141                 $site = "download.finance.yahoo.com";
142         //$filename = "/q?s={$curr_a}{$curr_b}=X"; // Let old code be here for a while, Joe.
143                 //$site = "finance.yahoo.com";
144         }
145         elseif ($provider == 'GOOGLE')
146         {
147                 $filename = "/finance/converter?a=1&from={$curr_a}&to={$curr_b}";
148                 $site = "www.google.com";
149         }
150         elseif ($provider == 'BLOOMBERG')
151         {
152                 $filename = "/quote/{$curr_b}{$curr_a}:CUR";
153                 $site = "www.bloomberg.com";
154         }
155         $contents = '';
156         if (function_exists('curl_init'))
157         {       // first check with curl as we can set short timeout;
158                 $retry = 1;
159                 do {
160                $ch = curl_init();
161            curl_setopt ($ch, CURLOPT_URL, 'http://'.$site.$filename);
162                curl_setopt ($ch, CURLOPT_COOKIEJAR, "$path_to_root/tmp/cookie.txt");
163            curl_setopt ($ch, CURLOPT_HEADER, 0);
164                curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
165                // prevent warning while safe_mode/open_basedir on (redireciton doesn't occur at least on ECB page)
166                    if (!ini_get('safe_mode') && !ini_get('open_basedir'))
167                 curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
168                curl_setopt ($ch, CURLOPT_TIMEOUT, 3);
169            $contents = curl_exec ($ch);
170                curl_close($ch);
171                         // due to resolver bug in some curl versions (e.g. 7.15.5) 
172                         // try again for constant IP.
173                    $site="172.230.157.137";
174            } while( ($contents == '') && $retry--);
175            
176         } else {
177                 $contents = url_get_contents("http://".$site.$filename);
178         }
179         if ($provider == 'ECB')
180         {
181                 $contents = str_replace ("<Cube currency='USD'", " <Cube currency='EUR' rate='1'/> <Cube currency='USD'", $contents);
182                 $from_mask = "|<Cube\s*currency=\'" . $curr_a . "\'\s*rate=\'([\d.,]*)\'\s*/>|i";
183                 preg_match ( $from_mask, $contents, $out );
184                 $val_a = isset($out[1]) ? $out[1] : 0;
185                 $val_a = str_replace ( ',', '', $val_a );
186                 $to_mask = "|<Cube\s*currency=\'" . $curr_b . "\'\s*rate=\'([\d.,]*)\'\s*/>|i";
187                 preg_match ( $to_mask, $contents, $out );
188                 $val_b = isset($out[1]) ? $out[1] : 0;
189                 $val_b = str_replace ( ',', '', $val_b );
190                 if ($val_b) 
191                 {
192                         $val = $val_a / $val_b;
193                 } 
194                 else 
195                 {
196                         $val = 0;
197                 }
198         }
199         elseif ($provider == 'YAHOO')
200         {
201                 $val = ''; 
202                 $array = explode(',',$contents); // New operations for YAHOO. Safer.
203                 $val = $array[1];
204                 if ($val != 0)
205                         $val = 1 / $val;
206                 /* Let old code be here for a while, Joe.
207                 //if (preg_match('/Last\sTrade:(.*?)Trade\sTime/s', $contents, $matches)) {
208                         $val = strip_tags($matches[1]);
209                         $val = str_replace(',', '', $val);
210                         if ($val != 0)
211                                 $val = 1 / $val;
212                 }
213                 */
214         }
215         elseif ($provider == 'GOOGLE')
216         {
217                 $val = '';
218                 
219                 $regexp = "%([\d|.]+)\s+{$curr_a}\s+=\s+<span\sclass=(.*)>([\d|.]+)\s+{$curr_b}\s*</span>%s";
220                 if (preg_match($regexp, $contents, $matches)) 
221                 {
222                         $val = $matches[3];
223                         $val = str_replace(',', '', $val);
224                         if ($val != 0)
225                                 $val = 1 / $val;
226                 }
227     }    
228         elseif ($provider == 'BLOOMBERG')
229         {
230                 $val = '';
231                 $stmask = '<span class=" price">';
232                 $val = trim(strstr($contents, $stmask));
233                 $stmask = chr(10);
234                 $val = trim(strstr($val, $stmask));
235                 $val = trim(strtok($val, $stmask)); 
236     }    
237         return $val;
238 }  /* end function get_extern_rate */
239
240 //-----------------------------------------------------------------------------
241
242 function get_sql_for_exchange_rates($curr)
243 {
244         $sql = "SELECT date_, rate_buy, id FROM "
245                 .TB_PREF."exchange_rates "
246                 ."WHERE curr_code=".db_escape($curr)."
247                  ORDER BY date_ DESC";
248         return $sql;     
249 }