897316d698e22e56c9dcfc8e3257971c555d81a1
[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 define('DB_DUPLICATE_ERROR', 1062);
13 define('SQL_MODE', ''); // STRICT_ALL_TABLES,NO_ZERO_IN_DATE ?
14
15 $db_last_inserted_id = 0;
16
17 function set_global_connection($company=-1)
18 {
19         global $db, $path_to_root, $db_connections, $SysPrefs;
20
21         include ($path_to_root . "/config_db.php");
22
23         if ($company == -1) 
24                 $company = user_company();
25
26         cancel_transaction(); // cancel all aborted transactions (if any)
27
28         $_SESSION["wa_current_user"]->cur_con = $company;
29
30         $connection = $db_connections[$company];
31
32         $db = mysqli_connect($connection["host"], $connection["dbuser"], $connection["dbpassword"]);
33                 mysqli_select_db($db, $connection["dbname"]);
34         ///// From mysqli release 5.6.6 the sql_mode is no longer empty as it was prior to
35         ///// this release. Just for safety we make it empty for all 5.6 release and higher.
36         ///// This non empty sql_mode values can interphere with FA, so all is set empty during
37         ///// our sessions.
38         ///// We are, however, investigating the existing code to be compatible in the future.
39         db_query("SET sql_mode = '".SQL_MODE."'");
40         /////
41         $SysPrefs->refresh();
42         return $db;
43 }
44
45 //DB wrapper functions to change only once for whole application
46
47 function db_query($sql, $err_msg=null)
48 {
49         global $db, $SysPrefs, $sql_queries, $Ajax,     $db_connections, $db_last_inserted_id;
50
51         // set current db prefix
52         $comp = isset($_SESSION["wa_current_user"]->cur_con) ? $_SESSION["wa_current_user"]->cur_con : 0;
53         $cur_prefix = $db_connections[$comp]['tbpref'];
54         $sql = str_replace(TB_PREF, $cur_prefix, $sql);
55
56         if ($SysPrefs->show_sql)
57         {
58                 $Ajax->activate('footer_debug');
59                 $sql_queries .= "<pre>$sql</pre>\n<hr>";
60         }
61
62         db_profile(); // mysql profiling
63
64         $retry = MAX_DEADLOCK_RETRY;
65         do {
66                 $result = mysqli_query($db, $sql);
67                 if (mysqli_errno($db) == 1213)  { // deadlock detected
68                         sleep(1); $retry--;
69                 } else
70                         $retry = 0;
71         } while ($retry);
72
73         db_profile($sql);
74
75         if($SysPrefs->sql_trail) {
76                 $db_last_inserted_id = mysqli_insert_id($db);   // preserve in case trail insert is done
77                 if ($SysPrefs->select_trail || (strstr($sql, 'SELECT') === false)) {
78                         mysqli_query($db, "INSERT INTO ".$cur_prefix."sql_trail
79                                 (`sql`, `result`, `msg`)
80                                 VALUES(".db_escape($sql).",".($result ? 1 : 0).",
81                                 ".db_escape($err_msg).")");
82                 }
83         }
84
85         if ($err_msg != null || $SysPrefs->go_debug) {
86                 $exit = $err_msg != null;
87                 if (function_exists('xdebug_call_file'))
88                         $err_msg = '<br>At file '.xdebug_call_file().':'.xdebug_call_line().':<br>'.$err_msg;
89                 check_db_error($err_msg, $sql, $exit);
90         }
91         return $result;
92 }
93
94 function db_fetch_row($result)
95 {
96         $ret = mysqli_fetch_row($result);
97         return ($ret === null ? false : $ret);
98 }
99
100 function db_fetch_assoc($result)
101 {
102         $ret = mysqli_fetch_assoc($result);
103         return ($ret === null ? false : $ret);
104 }
105
106 function db_fetch($result)
107 {
108         $ret = mysqli_fetch_array($result);
109         return ($ret === null ? false : $ret);
110 }
111
112 function db_seek(&$result,$record)
113 {
114         return mysqli_data_seek($result, $record);
115 }
116
117 function db_free_result($result)
118 {
119         if ($result)
120                 mysqli_free_result($result);
121 }
122
123 function db_num_rows($result)
124 {
125         return mysqli_num_rows($result);
126 }
127
128 function db_num_fields($result)
129 {
130         return mysqli_num_fields($result);
131 }
132
133 function db_escape($value = "", $nullify = false)
134 {
135         global $db;
136         
137         $value = @html_entity_decode($value, ENT_QUOTES, $_SESSION['language']->encoding);
138         $value = html_specials_encode($value);
139
140         //reset default if second parameter is skipped
141         $nullify = ($nullify === null) ? (false) : ($nullify);
142
143         //check for null/unset/empty strings
144         if ((!isset($value)) || (is_null($value)) || ($value === "")) {
145                 $value = ($nullify) ? ("NULL") : ("''");
146         } else {
147                 if (is_string($value)) {
148                         $value = "'" . mysqli_real_escape_string($db, $value) . "'";
149                 //value is a string and should be quoted; 
150                 } else if (!is_numeric($value)) {
151                         //value is not a string nor numeric
152                         display_error("ERROR: incorrect data type send to sql query");
153                         echo '<br><br>';
154                         exit();
155                 }
156         }
157         return $value;
158 }
159
160 function db_error_no()
161 {
162         global $db;
163     return mysqli_errno($db);
164 }
165
166 function db_error_msg($conn)
167 {
168         return mysqli_error($conn);
169 }
170
171 function db_insert_id()
172 {
173         global $db_last_inserted_id, $SysPrefs, $db;
174
175         return $SysPrefs->sql_trail ? $db_last_inserted_id : mysqli_insert_id($db);
176 }
177
178 function db_num_affected_rows()
179 {
180         global $db;
181         return mysqli_affected_rows($db);
182 }
183
184 function db_field_name($result, $n)
185 {
186     $fieldinfo = mysqli_fetch_field_direct($result, $n);
187     return $fieldinfo->name;
188 }
189
190 function db_set_collation($db, $fa_collation)
191 {
192         return mysqli_query($db, "ALTER DATABASE COLLATE ".get_mysql_collation($fa_collation));
193 }
194
195 /*
196         Create database for FA company. If database already exists,
197         just set collation to be sure nothing weird will happen later.
198 */
199 function db_create_db($connection)
200 {
201         global $db;
202
203         $db = mysqli_connect($connection["host"], $connection["dbuser"], $connection["dbpassword"]);
204
205         if (!mysqli_select_db($db, $connection["dbname"]))
206         {
207                 $sql = "CREATE DATABASE IF NOT EXISTS `" . $connection["dbname"] . "`"
208                         . " DEFAULT COLLATE '" . get_mysql_collation($connection["collation"]) . "'";
209
210                 if (!mysqli_query($db, $sql) || !mysqli_select_db($db, $connection["dbname"]))
211                         return 0;
212         } else {
213                 if (!db_set_collation($db, $connection["collation"]))
214                 {
215                         return 0;
216                 }
217         }
218         return $db;
219 }
220
221 function db_drop_db($connection)
222 {
223
224         if ($connection["tbpref"] == "")
225         {
226                 global $db;
227                 $sql = "DROP DATABASE IF EXISTS " . $connection["dbname"] . "";
228                 return mysqli_query($db, $sql);
229         }
230         else
231         {
232         $res = db_query("show table status");
233         $all_tables = array();
234         while($row = db_fetch($res))
235                 $all_tables[] = $row;
236         // get table structures
237                 foreach ($all_tables as $table)
238                 {
239                         if (strpos($table['Name'], $connection["tbpref"]) === 0)
240                                 db_query("DROP TABLE `".$table['Name'] . "`");
241                 }
242                 //deleting the tables, how??
243                 return true;
244         }
245 }
246
247 function db_close($dbase = null)
248 {
249         global $db;
250         
251         if (!$dbase)
252                 $dbase = $db;
253         return mysqli_close($dbase);
254 }
255
256 function db_extension_exists()
257 {
258         return function_exists('mysqli_connect');
259 }
260
261 function db_escape_function($string)
262 {
263         global $db;
264         
265         return (mysqli_real_escape_string($db, $string));
266 }
267
268 /*
269         Set mysql client encoding.
270         Default is is encoding used by default language.
271 */
272 function db_set_encoding($ui_encoding=null)
273 {
274         global $db, $dflt_lang, $installed_languages;
275
276         if (!isset($ui_encoding))
277         {
278                 $lang = array_search_value($dflt_lang, $installed_languages, 'code');
279                 $ui_encoding = strtoupper($lang['encoding']);
280         }
281
282         if ($mysql_enc = get_mysql_encoding_name($ui_encoding))
283                 mysqli_set_charset($db, $mysql_enc);
284 }
285
286 function db_get_charset($db)
287 {
288         return mysqli_character_set_name($db);
289 }
290
291 function db_set_charset($db, $charset)
292 {
293         global $db;
294
295         return mysqli_set_charset($db, $charset);
296 }