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