Old ineffective sql_trail superseded by new improved db_trail logging only calls...
[fa-stable.git] / includes / db / connect_db_mysql.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 function set_global_connection($company=-1)
16 {
17         global $db, $path_to_root, $db_connections, $SysPrefs;
18
19         include ($path_to_root . "/config_db.php");
20         if ($company == -1) 
21                 $company = user_company();
22
23         cancel_transaction(); // cancel all aborted transactions if any
24
25         $_SESSION["wa_current_user"]->cur_con = $company;
26
27         $connection = $db_connections[$company];
28         
29         $server = $connection["host"];
30         if (!empty($connection["port"]))
31                 $server .= ":".$connection["port"];
32
33         $db = mysql_connect($server, $connection["dbuser"], $connection["dbpassword"]);
34         mysql_select_db($connection["dbname"], $db);
35         ///// From MySql release 5.6.6 the sql_mode is no longer empty as it was prior to
36         ///// this release. Just for safety we make it empty for all 5.6 release and higher.
37         ///// This non empty sql_mode values can interphere with FA, so all is set empty during
38         ///// our sessions.
39         ///// We are, however, investigating the existing code to be compatible in the future.
40         db_query("SET sql_mode = '".SQL_MODE."'");
41         /////
42         $SysPrefs->refresh();
43         return $db;
44 }
45
46 //DB wrapper functions to change only once for whole application
47
48 function db_query($sql, $err_msg=null)
49 {
50         global $db, $SysPrefs, $sql_queries, $Ajax, $db_connections, $db_last_inserted_id;
51
52         // set current db prefix
53         $comp = isset($_SESSION["wa_current_user"]->cur_con) ? $_SESSION["wa_current_user"]->cur_con : 0;
54         $cur_prefix = $db_connections[$comp]['tbpref'];
55         $sql = str_replace(TB_PREF, $cur_prefix, $sql);
56
57         if ($SysPrefs->show_sql)
58         {
59                 $Ajax->activate('footer_debug');
60                 $sql_queries .= "<pre>$sql</pre>\n<hr>";
61         }
62
63         db_profile(); // mysql profiling
64
65         $retry = MAX_DEADLOCK_RETRY;
66         do {
67                 $result = mysql_query($db, $sql);
68                 if (mysql_errno($db) == 1213)   { // deadlock detected
69                         sleep(1); $retry--;
70                 } else
71                         $retry = 0;
72         } while ($retry);
73
74         if($SysPrefs->db_trail == 1)
75                 $db_last_inserted_id = mysql_insert_id($db);    // cache to avoid trail overwrite
76
77         db_profile($sql);
78
79         if ($err_msg != null || $SysPrefs->go_debug) {
80                 $exit = $err_msg != null;
81                 if (function_exists('xdebug_call_file'))
82                         $err_msg = '<br>At file '.xdebug_call_file().':'.xdebug_call_line().':<br>'.$err_msg;
83                 check_db_error($err_msg, $sql, $exit);
84         }
85         return $result;
86 }
87
88 function db_fetch_row($result)
89 {
90
91         return mysql_fetch_row($result);
92 }
93
94 function db_fetch_assoc($result)
95 {
96
97         return mysql_fetch_assoc($result);
98 }
99
100 function db_fetch($result)
101 {
102
103         return mysql_fetch_array($result);
104 }
105
106 function db_seek(&$result,$record)
107 {
108         return mysql_data_seek($result, $record);
109 }
110
111 function db_free_result($result)
112 {
113         if ($result)
114                 mysql_free_result($result);
115 }
116
117 function db_num_rows($result)
118 {
119         return mysql_num_rows($result);
120 }
121
122 function db_num_fields($result)
123 {
124         return mysql_num_fields($result);
125 }
126
127 function db_escape($value = "", $nullify = false)
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 is a string and should be quoted; determine best method based on available extensions
141                         if (function_exists('mysql_real_escape_string')) {
142                                 $value = "'" . mysql_real_escape_string($value) . "'";
143                         } else {
144                           $value = "'" . mysql_escape_string($value) . "'";
145                         }
146                 } else if (!is_numeric($value)) {
147                         //value is not a string nor numeric
148                         display_error("ERROR: incorrect data type send to sql query");
149                         echo '<br><br>';
150                         exit();
151                 }
152         }
153         return $value;
154 }
155
156 function db_error_no()
157 {
158         global $db;
159         return mysql_errno($db);
160 }
161
162 function db_error_msg($conn)
163 {
164         return mysql_error($conn);
165 }
166
167 function db_insert_id()
168 {
169         global $db_last_inserted_id, $SysPrefs, $db;
170
171         return $SysPrefs->db_trail == 1 ? $db_last_inserted_id : mysql_insert_id($db);
172 }
173
174 function db_num_affected_rows()
175 {
176         global $db;
177         return mysql_affected_rows($db);
178 }
179
180 function db_field_name($result, $n)
181 {
182         return mysql_field_name($result, $n);
183 }
184
185 function db_set_collation($db, $fa_collation)
186 {
187         return mysql_query("ALTER DATABASE COLLATE ".get_mysql_collation($fa_collation), $db);
188 }
189
190 /*
191         Create database for FA company. If database already exists,
192         just set collation to be sure nothing weird will happen later.
193 */
194 function db_create_db($connection)
195 {
196         $server = $connection["host"];
197         if (!empty($connection["port"]))
198                 $server .= ":".$connection["port"];
199         $db = mysql_connect($server, $connection["dbuser"], $connection["dbpassword"]);
200
201         if (!mysql_select_db($connection["dbname"], $db))
202         {
203                 $sql = "CREATE DATABASE IF NOT EXISTS `" . $connection["dbname"] . "`"
204                         . " DEFAULT COLLATE '" . get_mysql_collation($connection["collation"]) . "'";
205
206                 if (!mysql_query($sql) || !mysql_select_db($connection["dbname"], $db))
207                                 return 0;
208         } else
209                 if (!db_set_collation($connection["collation"], $db))
210                         return 0;
211
212         return $db;
213 }
214
215 function db_drop_db($connection)
216 {
217
218         if ($connection["tbpref"] == "")
219         {
220                 $sql = "DROP DATABASE IF EXISTS " . $connection["dbname"] . "";
221                 return mysql_query($sql);
222         }
223         else
224         {
225         $res = db_query("show table status");
226         $all_tables = array();
227         while($row = db_fetch($res))
228                 $all_tables[] = $row;
229         // get table structures
230                 foreach ($all_tables as $table)
231                 {
232                         if (strpos($table['Name'], $connection["tbpref"]) === 0)
233                                 db_query("DROP TABLE `".$table['Name'] . "`");
234                 }
235                 //deleting the tables, how??
236                 return true;
237         }
238 }
239
240 function db_close($dbase = null)
241 {
242         global $db;
243         
244         if (!$dbase)
245                 $dbase = $db;
246         return mysql_close($dbase);
247 }
248
249 function db_extension_exists()
250 {
251         return function_exists('mysql_connect');
252 }
253
254 function db_escape_function($string)
255 {
256         return (function_exists('mysql_real_escape_string') ? mysql_real_escape_string($string) : mysql_escape_string($string));
257 }
258
259 /*
260         Set mysql client encoding.
261         Default is is encoding used by default language.
262 */
263 function db_set_encoding($ui_encoding=null)
264 {
265         global $dflt_lang, $installed_languages;
266
267         if (!isset($ui_encoding))
268         {
269                 $lang = array_search_value($dflt_lang, $installed_languages, 'code');
270                 $ui_encoding = strtoupper($lang['encoding']);
271         }
272
273         if ($mysql_enc = get_mysql_encoding_name($ui_encoding))
274                 mysql_set_charset($mysql_enc);
275 }
276
277 function db_get_charset($db)
278 {
279         return mysql_client_encoding();
280 }
281
282 function db_set_charset($db, $charset)
283 {
284         return mysql_set_charset($charset, $db);
285 }