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