Merged changes form stabel branch up to the current state (2.3.22+).
[fa-stable.git] / includes / db / connect_db_mysqli.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 = mysqli_connect($connection["host"], $connection["dbuser"], $connection["dbpassword"]);
29                 mysqli_select_db($db, $connection["dbname"]);
30         ///// From mysqli 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 = mysqli_query($db, $sql);
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 = mysqli_insert_id($db);   // preserve in case trail insert is done
74                 if ($select_trail || (strstr($sql, 'SELECT') === false)) {
75                         mysqli_query($db, "INSERT INTO ".$cur_prefix."sql_trail
76                                 (`sql`, `result`, `msg`)
77                                 VALUES(".db_escape($sql).",".($result ? 1 : 0).",
78                                 ".db_escape($err_msg).")");
79                 }
80         }
81
82         if ($err_msg != null || $go_debug) {
83                 $exit = $err_msg != null;
84                 if (function_exists('xdebug_call_file'))
85                         check_db_error('<br>At file '.xdebug_call_file().':'.xdebug_call_line().':<br>'.$err_msg, $sql, $exit);
86                 else
87                         check_db_error($err_msg, $sql, $exit);
88         }
89         return $result;
90 }
91
92 function db_fetch_row ($result)
93 {
94         $ret = mysqli_fetch_row($result);
95         return ($ret === null ? false : $ret);
96 }
97
98 function db_fetch_assoc ($result)
99 {
100         $ret = mysqli_fetch_assoc($result);
101         return ($ret === null ? false : $ret);
102 }
103
104 function db_fetch ($result)
105 {
106         $ret = mysqli_fetch_array($result);
107         return ($ret === null ? false : $ret);
108 }
109
110 function db_seek (&$result,$record)
111 {
112         return mysqli_data_seek($result, $record);
113 }
114
115 function db_free_result ($result)
116 {
117         if ($result)
118                 mysqli_free_result($result);
119 }
120
121 function db_num_rows ($result)
122 {
123         return mysqli_num_rows($result);
124 }
125
126 function db_num_fields ($result)
127 {
128         return mysqli_num_fields($result);
129 }
130
131 function db_escape($value = "", $nullify = false)
132 {
133         global $db;
134         
135         $value = @html_entity_decode($value, ENT_QUOTES, $_SESSION['language']->encoding);
136         $value = @htmlspecialchars($value, ENT_QUOTES, $_SESSION['language']->encoding);
137
138         //reset default if second parameter is skipped
139         $nullify = ($nullify === null) ? (false) : ($nullify);
140
141         //check for null/unset/empty strings
142         if ((!isset($value)) || (is_null($value)) || ($value === "")) {
143                 $value = ($nullify) ? ("NULL") : ("''");
144         } else {
145                 if (is_string($value)) {
146                         $value = "'" . mysqli_real_escape_string($db, $value) . "'";
147                 //value is a string and should be quoted; 
148                 } else if (!is_numeric($value)) {
149                         //value is not a string nor numeric
150                         display_error("ERROR: incorrect data type send to sql query");
151                         echo '<br><br>';
152                         exit();
153                 }
154         }
155         return $value;
156 }
157
158 function db_error_no ()
159 {
160         global $db;
161     return mysqli_errno($db);
162 }
163
164 function db_error_msg($conn)
165 {
166         return mysqli_error($conn);
167 }
168
169 function db_insert_id()
170 {
171         global $db_last_inserted_id, $sql_trail, $db;
172
173         return $sql_trail ? $db_last_inserted_id : mysqli_insert_id($db);
174 }
175
176 function db_num_affected_rows()
177 {
178         global $db;
179         return mysqli_affected_rows($db);
180 }
181
182 function db_field_name($result, $n)
183 {
184     $fieldinfo = mysqli_fetch_field_direct($result, $n);
185     return $fieldinfo->name;
186 }
187
188 function db_create_db($connection)
189 {
190         $db = mysqli_connect($connection["host"], $connection["dbuser"], $connection["dbpassword"]);
191         if (strncmp(db_get_version(), "5.6", 3) >= 0) 
192                 db_query("SET sql_mode = ''");
193         if (!mysqli_select_db($db, $connection["dbname"]))
194         {
195                 $sql = "CREATE DATABASE IF NOT EXISTS " . $connection["dbname"] . "";
196                 if (!mysqli_query($db, $sql) || !mysqli_select_db($db, $connection["dbname"]))
197                         return 0;
198         }
199         return $db;
200 }
201
202 function db_drop_db($connection)
203 {
204
205         if ($connection["tbpref"] == "")
206         {
207                 global $db;
208                 $sql = "DROP DATABASE IF EXISTS " . $connection["dbname"] . "";
209                 return mysqli_query($db, $sql);
210         }
211         else
212         {
213         $res = db_query("show table status");
214         $all_tables = array();
215         while($row = db_fetch($res))
216                 $all_tables[] = $row;
217         // get table structures
218                 foreach ($all_tables as $table)
219                 {
220                         if (strpos($table['Name'], $connection["tbpref"]) === 0)
221                                 db_query("DROP TABLE `".$table['Name'] . "`");
222                 }
223                 //deleting the tables, how??
224                 return true;
225         }
226 }
227
228 function db_close($dbase = null)
229 {
230         global $db;
231         
232         if (!$dbase)
233                 $dbase = $db;
234         return mysqli_close($dbase);
235 }
236
237 function db_extension_exists()
238 {
239         return function_exists('mysqli_connect');
240 }
241
242 function db_escape_function($string)
243 {
244         global $db;
245         
246         return (mysqli_real_escape_string($db, $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 $db, $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                 mysqli_set_charset($db, $mysql_enc);
265 }
266
267 function db_get_charset($db)
268 {
269         return mysqli_character_set_name($db);
270 }
271
272 function db_set_charset($db, $charset)
273 {
274         global $db;
275
276         return mysqli_set_charset($db, $charset);
277 }