Rewritten upgrade procedures, added fa_patch class, utf8 collation can be set before...
[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         refresh_sys_prefs();
41         return $db;
42 }
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, $SysPrefs, $sql_queries, $Ajax,     $db_connections, $db_last_inserted_id;
49
50         // set current db prefix
51         $comp = isset($_SESSION["wa_current_user"]->cur_con) ? $_SESSION["wa_current_user"]->cur_con : 0;
52         $cur_prefix = $db_connections[$comp]['tbpref'];
53         $sql = str_replace(TB_PREF, $cur_prefix, $sql);
54
55         if ($SysPrefs->show_sql)
56         {
57                 $Ajax->activate('footer_debug');
58                 $sql_queries .= "<pre>$sql</pre>\n<hr>";
59         }
60
61         db_profile(); // mysql profiling
62
63         $result = mysqli_query($db, $sql);
64
65         db_profile($sql);
66
67         if($SysPrefs->sql_trail) {
68                 $db_last_inserted_id = mysqli_insert_id($db);   // preserve in case trail insert is done
69                 if ($SysPrefs->select_trail || (strstr($sql, 'SELECT') === false)) {
70                         mysqli_query($db, "INSERT INTO ".$cur_prefix."sql_trail
71                                 (`sql`, `result`, `msg`)
72                                 VALUES(".db_escape($sql).",".($result ? 1 : 0).",
73                                 ".db_escape($err_msg).")");
74                 }
75         }
76
77         if ($err_msg != null || $SysPrefs->go_debug) {
78                 $exit = $err_msg != null;
79                 if (function_exists('xdebug_call_file'))
80                         check_db_error('<br>At file '.xdebug_call_file().':'.xdebug_call_line().':<br>'.$err_msg, $sql, $exit);
81                 else
82                         check_db_error($err_msg, $sql, $exit);
83         }
84         return $result;
85 }
86
87 function db_fetch_row ($result)
88 {
89         $ret = mysqli_fetch_row($result);
90         return ($ret === null ? false : $ret);
91 }
92
93 function db_fetch_assoc ($result)
94 {
95         $ret = mysqli_fetch_assoc($result);
96         return ($ret === null ? false : $ret);
97 }
98
99 function db_fetch ($result)
100 {
101         $ret = mysqli_fetch_array($result);
102         return ($ret === null ? false : $ret);
103 }
104
105 function db_seek (&$result,$record)
106 {
107         return mysqli_data_seek($result, $record);
108 }
109
110 function db_free_result ($result)
111 {
112         if ($result)
113                 mysqli_free_result($result);
114 }
115
116 function db_num_rows ($result)
117 {
118         return mysqli_num_rows($result);
119 }
120
121 function db_num_fields ($result)
122 {
123         return mysqli_num_fields($result);
124 }
125
126 function db_escape($value = "", $nullify = false)
127 {
128         global $db;
129         
130         $value = @html_entity_decode($value, ENT_QUOTES, $_SESSION['language']->encoding);
131         $value = html_specials_encode($value);
132
133         //reset default if second parameter is skipped
134         $nullify = ($nullify === null) ? (false) : ($nullify);
135
136         //check for null/unset/empty strings
137         if ((!isset($value)) || (is_null($value)) || ($value === "")) {
138                 $value = ($nullify) ? ("NULL") : ("''");
139         } else {
140                 if (is_string($value)) {
141                         $value = "'" . mysqli_real_escape_string($db, $value) . "'";
142                 //value is a string and should be quoted; 
143                 } else if (!is_numeric($value)) {
144                         //value is not a string nor numeric
145                         display_error("ERROR: incorrect data type send to sql query");
146                         echo '<br><br>';
147                         exit();
148                 }
149         }
150         return $value;
151 }
152
153 function db_error_no ()
154 {
155         global $db;
156     return mysqli_errno($db);
157 }
158
159 function db_error_msg($conn)
160 {
161         return mysqli_error($conn);
162 }
163
164 function db_insert_id()
165 {
166         global $db_last_inserted_id, $SysPrefs, $db;
167
168         return $SysPrefs->sql_trail ? $db_last_inserted_id : mysqli_insert_id($db);
169 }
170
171 function db_num_affected_rows()
172 {
173         global $db;
174         return mysqli_affected_rows($db);
175 }
176
177 function db_field_name($result, $n)
178 {
179     $fieldinfo = mysqli_fetch_field_direct($result, $n);
180     return $fieldinfo->name;
181 }
182
183 function db_create_db($connection)
184 {
185         $db = mysqli_connect($connection["host"], $connection["dbuser"], $connection["dbpassword"]);
186
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 }