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