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
15 $db_last_inserted_id = 0;
17 function set_global_connection($company=-1)
19 global $db, $path_to_root, $db_connections, $SysPrefs;
21 include ($path_to_root . "/config_db.php");
24 $company = user_company();
26 cancel_transaction(); // cancel all aborted transactions (if any)
28 $_SESSION["wa_current_user"]->cur_con = $company;
30 if (!is_string($db_connections[$company]['tbpref']))
31 $db_connections[$company]['tbpref'] = '';
33 $connection = $db_connections[$company];
35 $db = mysqli_connect($connection["host"], $connection["dbuser"], $connection["dbpassword"], "",
36 !empty($connection["port"]) ? $connection["port"] : 3306); // default port in mysql is 3306
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
43 ///// We are, however, investigating the existing code to be compatible in the future.
44 db_query("SET sql_mode = '".SQL_MODE."'");
50 //DB wrapper functions to change only once for whole application
52 function db_query($sql, $err_msg=null)
54 global $db, $SysPrefs, $sql_queries, $Ajax, $db_connections, $db_last_inserted_id;
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);
61 if ($SysPrefs->show_sql)
63 $Ajax->activate('footer_debug');
64 $sql_queries .= "<pre>$sql</pre>\n<hr>";
67 db_profile(); // mysql profiling
69 $retry = MAX_DEADLOCK_RETRY;
71 $result = mysqli_query($db, $sql);
72 if (mysqli_errno($db) == 1213) { // deadlock detected
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).")");
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);
99 function db_fetch_row($result)
101 $ret = mysqli_fetch_row($result);
102 return ($ret === null ? false : $ret);
105 function db_fetch_assoc($result)
107 $ret = mysqli_fetch_assoc($result);
108 return ($ret === null ? false : $ret);
111 function db_fetch($result)
113 $ret = mysqli_fetch_array($result);
114 return ($ret === null ? false : $ret);
117 function db_seek(&$result,$record)
119 return mysqli_data_seek($result, $record);
122 function db_free_result($result)
125 mysqli_free_result($result);
128 function db_num_rows($result)
130 return mysqli_num_rows($result);
133 function db_num_fields($result)
135 return mysqli_num_fields($result);
138 function db_escape($value = "", $nullify = false)
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);
145 //reset default if second parameter is skipped
146 $nullify = ($nullify === null) ? (false) : ($nullify);
148 //check for null/unset/empty strings
149 if ((!isset($value)) || (is_null($value)) || ($value === "")) {
150 $value = ($nullify) ? ("NULL") : ("''");
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");
165 function db_error_no()
168 return mysqli_errno($db);
171 function db_error_msg($conn)
173 return mysqli_error($conn);
176 function db_insert_id()
178 global $db_last_inserted_id, $SysPrefs, $db;
180 return $SysPrefs->sql_trail ? $db_last_inserted_id : mysqli_insert_id($db);
183 function db_num_affected_rows()
186 return mysqli_affected_rows($db);
189 function db_field_name($result, $n)
191 $fieldinfo = mysqli_fetch_field_direct($result, $n);
192 return $fieldinfo->name;
195 function db_set_collation($db, $fa_collation)
197 return mysqli_query($db, "ALTER DATABASE COLLATE ".get_mysql_collation($fa_collation));
201 Create database for FA company. If database already exists,
202 just set collation to be sure nothing weird will happen later.
204 function db_create_db($connection)
208 $db = mysqli_connect($connection["host"], $connection["dbuser"], $connection["dbpassword"], "",
209 !empty($connection["port"]) ? $connection["port"] : 3306); // default port in mysql is 3306
211 if (!mysqli_select_db($db, $connection["dbname"]))
213 $sql = "CREATE DATABASE IF NOT EXISTS `" . $connection["dbname"] . "`"
214 . " DEFAULT COLLATE '" . get_mysql_collation($connection["collation"]) . "'";
216 if (!mysqli_query($db, $sql) || !mysqli_select_db($db, $connection["dbname"]))
219 if (!db_set_collation($db, $connection["collation"]))
227 function db_drop_db($connection)
230 if ($connection["tbpref"] == "")
233 $sql = "DROP DATABASE IF EXISTS " . $connection["dbname"] . "";
234 return mysqli_query($db, $sql);
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)
245 if (strpos($table['Name'], $connection["tbpref"]) === 0)
246 db_query("DROP TABLE `".$table['Name'] . "`");
248 //deleting the tables, how??
253 function db_close($dbase = null)
259 return mysqli_close($dbase);
262 function db_extension_exists()
264 return function_exists('mysqli_connect');
267 function db_escape_function($string)
271 return (mysqli_real_escape_string($db, $string));
275 Set mysql client encoding.
276 Default is is encoding used by default language.
278 function db_set_encoding($ui_encoding=null)
280 global $db, $dflt_lang, $installed_languages;
282 if (!isset($ui_encoding))
284 $lang = array_search_value($dflt_lang, $installed_languages, 'code');
285 $ui_encoding = strtoupper($lang['encoding']);
288 if ($mysql_enc = get_mysql_encoding_name($ui_encoding))
289 mysqli_set_charset($db, $mysql_enc);
292 function db_get_charset($db)
294 return mysqli_character_set_name($db);
297 function db_set_charset($db, $charset)
301 return mysqli_set_charset($db, $charset);