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