Stable branch merged up to 2.3.21
[fa-stable.git] / includes / db / connect_db_mysql.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 set_global_connection($company=-1)
14 {
15         global $db, $transaction_level, $path_to_root, $db_connections;
16
17         include ($path_to_root . "/config_db.php");
18         if ($company == -1) 
19                 $company = $_SESSION["wa_current_user"]->company;
20
21         cancel_transaction(); // cancel all aborted transactions if any
22         $transaction_level = 0;
23
24         $_SESSION["wa_current_user"]->cur_con = $company;
25
26         $connection = $db_connections[$company];
27
28         $db = mysql_connect($connection["host"], $connection["dbuser"], $connection["dbpassword"]);
29                 mysql_select_db($connection["dbname"], $db);
30         ///// From MySql release 5.6.6 the sql_mode is no longer empty as it was prior to
31         ///// this release. Just for safety we make it empty for all 5.6 release and higher.
32         ///// This non empty sql_mode values can interphere with FA, so all is set empty during
33         ///// our sessions.
34         ///// We are, however, investigating the existing code to be compatible in the future.
35         if (strncmp(db_get_version(), "5.6", 3) >= 0) 
36                 db_query("SET sql_mode = ''");
37         /////
38         return $db;
39 }
40
41 $db_duplicate_error_code = 1062;
42
43 //DB wrapper functions to change only once for whole application
44
45 function db_query($sql, $err_msg=null)
46 {
47         global $db, $show_sql, $sql_trail, $select_trail, $go_debug, $sql_queries, $Ajax,
48                 $db_connections, $db_last_inserted_id;
49         
50         // set current db prefix
51         $comp = isset($_SESSION["wa_current_user"]->cur_con) ? $_SESSION["wa_current_user"]->cur_con : 0;
52         $cur_prefix = $db_connections[$comp]['tbpref'];
53         $sql = str_replace(TB_PREF, $cur_prefix, $sql);
54
55         if ($show_sql)
56         {
57                 $Ajax->activate('footer_debug');
58                 $sql_queries .= "<pre>$sql</pre>\n<hr>";
59         }
60
61         // mysql profiling
62         global $profile_sql;
63         if (@$profile_sql) 
64                 get_usec();
65         $result = mysql_query($sql, $db);
66         if (@$profile_sql)
67         {
68                 $profile_sql= false;
69                 _vd($sql.'<br>:'.db_num_rows($result).'rows, '.get_usec());
70         }
71         
72         if($sql_trail) {
73                 $db_last_inserted_id = mysql_insert_id($db);    // preserve in case trail insert is done
74                 if ($select_trail || (strstr($sql, 'SELECT') === false)) {
75                         mysql_query(
76                         "INSERT INTO ".$cur_prefix."sql_trail
77                                 (`sql`, `result`, `msg`)
78                                 VALUES(".db_escape($sql).",".($result ? 1 : 0).",
79                                 ".db_escape($err_msg).")", $db);
80                 }
81         }
82
83         if ($err_msg != null || $go_debug) {
84                 $exit = $err_msg != null;
85                 if (function_exists('xdebug_call_file'))
86                         check_db_error('<br>At file '.xdebug_call_file().':'.xdebug_call_line().':<br>'.$err_msg, $sql, $exit);
87                 else
88                         check_db_error($err_msg, $sql, $exit);
89         }
90         return $result;
91 }
92
93 function db_fetch_row ($result)
94 {
95
96         return mysql_fetch_row($result);
97 }
98
99 function db_fetch_assoc ($result)
100 {
101
102         return mysql_fetch_assoc($result);
103 }
104
105 function db_fetch ($result)
106 {
107
108         return mysql_fetch_array($result);
109 }
110
111 function db_seek (&$result,$record)
112 {
113         return mysql_data_seek($result, $record);
114 }
115
116 function db_free_result ($result)
117 {
118         if ($result)
119                 mysql_free_result($result);
120 }
121
122 function db_num_rows ($result)
123 {
124         return mysql_num_rows($result);
125 }
126
127 function db_num_fields ($result)
128 {
129         return mysql_num_fields($result);
130 }
131
132 function db_escape($value = "", $nullify = false)
133 {
134         $value = @html_entity_decode($value, ENT_QUOTES, $_SESSION['language']->encoding);
135         $value = @htmlspecialchars($value, ENT_QUOTES, $_SESSION['language']->encoding);
136
137         //reset default if second parameter is skipped
138         $nullify = ($nullify === null) ? (false) : ($nullify);
139
140         //check for null/unset/empty strings
141         if ((!isset($value)) || (is_null($value)) || ($value === "")) {
142                 $value = ($nullify) ? ("NULL") : ("''");
143         } else {
144                 if (is_string($value)) {
145                 //value is a string and should be quoted; determine best method based on available extensions
146                         if (function_exists('mysql_real_escape_string')) {
147                                 $value = "'" . mysql_real_escape_string($value) . "'";
148                         } else {
149                           $value = "'" . mysql_escape_string($value) . "'";
150                         }
151                 } else if (!is_numeric($value)) {
152                         //value is not a string nor numeric
153                         display_error("ERROR: incorrect data type send to sql query");
154                         echo '<br><br>';
155                         exit();
156                 }
157         }
158         return $value;
159 }
160
161 function db_error_no ()
162 {
163         global $db;
164         return mysql_errno($db);
165 }
166
167 function db_error_msg($conn)
168 {
169         return mysql_error($conn);
170 }
171
172 function db_insert_id()
173 {
174         global $db_last_inserted_id, $sql_trail, $db;
175
176         return $sql_trail ? $db_last_inserted_id : mysql_insert_id($db);
177 }
178
179 function db_num_affected_rows()
180 {
181         global $db;
182         return mysql_affected_rows($db);
183 }
184
185 function db_field_name($result, $n)
186 {
187         return mysql_field_name($result, $n);
188 }
189
190 function db_create_db($connection)
191 {
192         $db = mysql_connect($connection["host"] ,
193                 $connection["dbuser"], $connection["dbpassword"]);
194         if (strncmp(db_get_version(), "5.6", 3) >= 0) 
195                 db_query("SET sql_mode = ''");
196         if (!mysql_select_db($connection["dbname"], $db))
197         {
198                 $sql = "CREATE DATABASE IF NOT EXISTS " . $connection["dbname"] . "";
199                 if (!mysql_query($sql) || !mysql_select_db($connection["dbname"], $db))
200                         return 0;
201         }
202         return $db;
203 }
204
205 function db_drop_db($connection)
206 {
207
208         if ($connection["tbpref"] == "")
209         {
210                 $sql = "DROP DATABASE IF EXISTS " . $connection["dbname"] . "";
211                 return mysql_query($sql);
212         }
213         else
214         {
215         $res = db_query("show table status");
216         $all_tables = array();
217         while($row = db_fetch($res))
218                 $all_tables[] = $row;
219         // get table structures
220                 foreach ($all_tables as $table)
221                 {
222                         if (strpos($table['Name'], $connection["tbpref"]) === 0)
223                                 db_query("DROP TABLE `".$table['Name'] . "`");
224                 }
225                 //deleting the tables, how??
226                 return true;
227         }
228 }
229
230 function db_close($dbase = null)
231 {
232         global $db;
233         
234         if (!$dbase)
235                 $dbase = $db;
236         return mysql_close($dbase);
237 }
238
239 function db_extension_exists()
240 {
241         return function_exists('mysql_connect');
242 }
243
244 function db_escape_function($string)
245 {
246         return (function_exists('mysql_real_escape_string') ? mysql_real_escape_string($string) : mysql_escape_string($string));
247 }
248
249 /*
250         Set mysql client encoding.
251         Default is is encoding used by default language.
252 */
253 function db_set_encoding($ui_encoding=null)
254 {
255         global $dflt_lang, $installed_languages;
256
257         if (!isset($ui_encoding))
258         {
259                 $lang = array_search_value($dflt_lang, $installed_languages, 'code');
260                 $ui_encoding = strtoupper($lang['encoding']);
261         }
262
263         if ($mysql_enc = get_mysql_encoding_name($ui_encoding))
264                 mysql_set_charset($mysql_enc);
265 }
266
267 ?>