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