Merged changes from main trunk 2.2.1-2.2.2
[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 //---------------------------------------------------------------------------------------------
13 function get_exchange_rate($rate_id)
14 {
15         $sql = "SELECT * FROM ".TB_PREF."exchange_rates WHERE id=".db_escape($rate_id);
16         $result = db_query($sql, "could not get exchange rate for $rate_id");   
17
18         return db_fetch($result);
19 }
20
21 // Retrieves buy exchange rate for given currency/date, zero if no result
22 function get_date_exchange_rate($curr_code, $date_)
23 {
24         $date = date2sql($date_);
25         $sql = "SELECT rate_buy FROM ".TB_PREF."exchange_rates WHERE curr_code=".db_escape($curr_code)
26         ." AND date_='$date'";
27         $result = db_query($sql, "could not get exchange rate for $curr_code - $date_");        
28
29         if(db_num_rows($result) == 0) 
30                 return 0;
31         $row = db_fetch($result);
32                 return $row[0];
33 }
34
35 //---------------------------------------------------------------------------------------------
36
37 function update_exchange_rate($curr_code, $date_, $buy_rate, $sell_rate)
38 {
39         if (is_company_currency($curr_code))
40                 display_db_error("Exchange rates cannot be set for company currency", "", true);
41                         
42         $date = date2sql($date_);
43                 
44         $sql = "UPDATE ".TB_PREF."exchange_rates SET rate_buy=$buy_rate, rate_sell=".db_escape($sell_rate)
45         ." WHERE curr_code=".db_escape($curr_code)." AND date_='$date'";
46                                 
47         db_query($sql, "could not add exchange rate for $curr_code");                           
48 }
49
50 //---------------------------------------------------------------------------------------------
51
52 function add_exchange_rate($curr_code, $date_, $buy_rate, $sell_rate)
53 {
54         if (is_company_currency($curr_code))
55                 display_db_error("Exchange rates cannot be set for company currency", "", true);
56
57         $date = date2sql($date_);
58                 
59         $sql = "INSERT INTO ".TB_PREF."exchange_rates (curr_code, date_, rate_buy, rate_sell)
60                 VALUES (".db_escape($curr_code).", '$date', ".db_escape($buy_rate)
61                 .", ".db_escape($sell_rate).")";
62         db_query($sql, "could not add exchange rate for $curr_code");                           
63 }
64
65 //---------------------------------------------------------------------------------------------
66
67 function delete_exchange_rate($rate_id)
68 {
69         $sql = "DELETE FROM ".TB_PREF."exchange_rates WHERE id=".db_escape($rate_id);
70         db_query($sql, "could not delete exchange rate $rate_id");              
71 }
72
73 //-----------------------------------------------------------------------------
74 //      Retrieve exchange rate as of date $date from external source (usually inet)
75 //
76 function retrieve_exrate($curr_b, $date)
77 {
78         global $Hooks;
79
80         if (method_exists($Hooks, 'retrieve_exrate'))
81                 return $Hooks->retrieve_exrate($curr_b, $date);
82         else
83                 return get_extern_rate($curr_b, 'ECB', $date);
84 }
85 //-----------------------------------------------------------------------------
86
87 function get_extern_rate($curr_b, $provider = 'ECB', $date) 
88 {
89         $curr_a = get_company_pref('curr_default');
90         if ($provider == 'ECB')
91         {
92                 $filename = "/stats/eurofxref/eurofxref-daily.xml";
93                 $site = "www.ecb.int";
94         }
95         elseif ($provider == 'YAHOO')
96         {
97                 $filename = "/q?s={$curr_a}{$curr_b}=X";
98                 $site = "finance.yahoo.com";
99         }
100         elseif ($provider == 'GOOGLE')
101         {
102                 $filename = "/finance/converter?a=1&from={$curr_a}&to={$curr_b}";
103                 $site = "finance.google.com";
104         }
105         $contents = '';
106
107         if (function_exists('curl_init'))
108         {       // first check with curl as we can set short timeout;
109                 $retry = 1;
110                 do {
111                $ch = curl_init();
112            curl_setopt ($ch, CURLOPT_URL, 'http://'.$site.$filename);
113                curl_setopt ($ch, CURLOPT_COOKIEJAR, "cookie.txt");
114            curl_setopt ($ch, CURLOPT_HEADER, 0);
115                curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
116            curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
117                curl_setopt ($ch, CURLOPT_TIMEOUT, 3);
118            $contents = curl_exec ($ch);
119                curl_close($ch);
120                         // due to resolver bug in some curl versions (e.g. 7.15.5) 
121                         // try again for constant IP.
122                    $site="195.128.2.97";
123            } while( ($contents == '') && $retry--);
124            
125         } else {
126                 $handle = @fopen("http://".$site.$filename, 'rb');
127                 if ($handle) {
128                         do 
129                         {
130                                 $data = @fread( $handle, 4096 );
131                                 if ( strlen ( $data ) == 0 ) 
132                                         break;
133                                 $contents .= $data; // with this syntax only text will be translated, whole text with htmlspecialchars($data)
134                         } 
135                         while (true);
136                         @fclose( $handle );
137                 } // end handle
138         }
139         if (!$contents) {
140                 display_warning(_("Cannot retrieve currency rate from $provider page. Please set the rate manually."));
141         }
142         if ($provider == 'ECB')
143         {
144                 $contents = str_replace ("<Cube currency='USD'", " <Cube currency='EUR' rate='1'/> <Cube currency='USD'", $contents);
145                 $from_mask = "|<Cube\s*currency=\'" . $curr_a . "\'\s*rate=\'([\d.,]*)\'\s*/>|i";
146                 preg_match ( $from_mask, $contents, $out );
147                 $val_a = isset($out[1]) ? $out[1] : 0;
148                 $val_a = str_replace ( ',', '', $val_a );
149                 $to_mask = "|<Cube\s*currency=\'" . $curr_b . "\'\s*rate=\'([\d.,]*)\'\s*/>|i";
150                 preg_match ( $to_mask, $contents, $out );
151                 $val_b = isset($out[1]) ? $out[1] : 0;
152                 $val_b = str_replace ( ',', '', $val_b );
153                 if ($val_b) 
154                 {
155                         $val = $val_a / $val_b;
156                 } 
157                 else 
158                 {
159                         $val = 0;
160                 }
161         }
162         elseif ($provider == 'YAHOO')
163         {
164                 $val = '';
165                 if (preg_match('/Last\sTrade:(.*?)Trade\sTime/s', $contents, $matches)) {
166                         $val = strip_tags($matches[1]);
167                         $val = str_replace(',', '', $val);
168                         if ($val != 0)
169                                 $val = 1 / $val;
170                 }
171         }
172         elseif ($provider == 'GOOGLE')
173         {
174                 $val = '';
175                 $regexp = "%([\d|.]+)\s+{$curr_a}\s+=\s+<span\sclass=(.*)>([\d|.]+)\s+{$curr_b}\s*</span>%s";
176                 if (preg_match($regexp, $contents, $matches)) 
177                 {
178                         $val = $matches[3];
179                         $val = str_replace(',', '', $val);
180                         if ($val != 0)
181                                 $val = 1 / $val;
182                 }
183     }    
184         return $val;
185 }  /* end function get_extern_rate */
186
187 //-----------------------------------------------------------------------------
188
189 function get_sql_for_exchange_rates()
190 {
191         $sql = "SELECT date_, rate_buy, id FROM "
192                 .TB_PREF."exchange_rates "
193                 ."WHERE curr_code=".db_escape($_POST['curr_abrev'])."
194                  ORDER BY date_ DESC";
195         return $sql;     
196 }
197 ?>