56e36a0ae9d95650b05c7c8f7cae3ff2328067c5
[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,NO_ZERO_IN_DATE ?
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         $db = mysql_connect($connection["host"], $connection["dbuser"], $connection["dbpassword"]);
30                 mysql_select_db($connection["dbname"], $db);
31         ///// From MySql 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         db_query("SET sql_mode = '".SQL_MODE."'");
37         /////
38         $SysPrefs->refresh();
39         return $db;
40 }
41
42 //DB wrapper functions to change only once for whole application
43
44 function db_query($sql, $err_msg=null)
45 {
46         global $db, $SysPrefs, $sql_queries, $Ajax, $db_connections, $db_last_inserted_id;
47
48         // set current db prefix
49         $comp = isset($_SESSION["wa_current_user"]->cur_con) ? $_SESSION["wa_current_user"]->cur_con : 0;
50         $cur_prefix = $db_connections[$comp]['tbpref'];
51         $sql = str_replace(TB_PREF, $cur_prefix, $sql);
52
53         if ($SysPrefs->show_sql)
54         {
55                 $Ajax->activate('footer_debug');
56                 $sql_queries .= "<pre>$sql</pre>\n<hr>";
57         }
58
59         db_profile(); // mysql profiling
60
61         $retry = MAX_DEADLOCK_RETRY;
62         do {
63                 $result = mysql_query($db, $sql);
64                 if (mysql_errno($db) == 1213)   { // deadlock detected
65                         sleep(1); $retry--;
66                 } else
67                         $retry = 0;
68         } while ($retry);
69
70         db_profile($sql);
71
72         if($SysPrefs->sql_trail) {
73                 $db_last_inserted_id = mysql_insert_id($db);    // preserve in case trail insert is done
74                 if ($SysPrefs->select_trail || (strstr($sql, 'SELECT') === false)) {
75                         mysql_query(
76                         "INSERT INTO ".$cur_prefix."sql_trail
77                                 (`sql`, `result`, `msg`)
78                                 VALUES(".db_escape($sql).",".($result ? 1 : 0).",
79                                 ".db_escape($err_msg).")", $db);
80                 }
81         }
82
83         if ($err_msg != null || $SysPrefs->go_debug) {
84                 $exit = $err_msg != null;
85                 if (function_exists('xdebug_call_file'))
86                         $err_msg = '<br>At file '.xdebug_call_file().':'.xdebug_call_line().':<br>'.$err_msg;
87                 check_db_error($err_msg, $sql, $exit);
88         }
89         return $result;
90 }
91
92 function db_fetch_row($result)
93 {
94
95         return mysql_fetch_row($result);
96 }
97
98 function db_fetch_assoc($result)
99 {
100
101         return mysql_fetch_assoc($result);
102 }
103
104 function db_fetch($result)
105 {
106
107         return mysql_fetch_array($result);
108 }
109
110 function db_seek(&$result,$record)
111 {
112         return mysql_data_seek($result, $record);
113 }
114
115 function db_free_result($result)
116 {
117         if ($result)
118                 mysql_free_result($result);
119 }
120
121 function db_num_rows($result)
122 {
123         return mysql_num_rows($result);
124 }
125
126 function db_num_fields($result)
127 {
128         return mysql_num_fields($result);
129 }
130
131 function db_escape($value = "", $nullify = false)
132 {
133         $value = @html_entity_decode($value, ENT_QUOTES, $_SESSION['language']->encoding);
134         $value = html_specials_encode($value);
135
136         //reset default if second parameter is skipped
137         $nullify = ($nullify === null) ? (false) : ($nullify);
138
139         //check for null/unset/empty strings
140         if ((!isset($value)) || (is_null($value)) || ($value === "")) {
141                 $value = ($nullify) ? ("NULL") : ("''");
142         } else {
143                 if (is_string($value)) {
144                 //value is a string and should be quoted; determine best method based on available extensions
145                         if (function_exists('mysql_real_escape_string')) {
146                                 $value = "'" . mysql_real_escape_string($value) . "'";
147                         } else {
148                           $value = "'" . mysql_escape_string($value) . "'";
149                         }
150                 } else if (!is_numeric($value)) {
151                         //value is not a string nor numeric
152                         display_error("ERROR: incorrect data type send to sql query");
153                         echo '<br><br>';
154                         exit();
155                 }
156         }
157         return $value;
158 }
159
160 function db_error_no()
161 {
162         global $db;
163         return mysql_errno($db);
164 }
165
166 function db_error_msg($conn)
167 {
168         return mysql_error($conn);
169 }
170
171 function db_insert_id()
172 {
173         global $db_last_inserted_id, $SysPrefs, $db;
174
175         return $SysPrefs->sql_trail ? $db_last_inserted_id : mysql_insert_id($db);
176 }
177
178 function db_num_affected_rows()
179 {
180         global $db;
181         return mysql_affected_rows($db);
182 }
183
184 function db_field_name($result, $n)
185 {
186         return mysql_field_name($result, $n);
187 }
188
189 function db_set_collation($db, $fa_collation)
190 {
191         return mysql_query("ALTER DATABASE COLLATE ".get_mysql_collation($fa_collation), $db);
192 }
193
194 /*
195         Create database for FA company. If database already exists,
196         just set collation to be sure nothing weird will happen later.
197 */
198 function db_create_db($connection)
199 {
200         $db = mysql_connect($connection["host"] ,
201                 $connection["dbuser"], $connection["dbpassword"]);
202
203         if (!mysql_select_db($connection["dbname"], $db))
204         {
205                 $sql = "CREATE DATABASE IF NOT EXISTS `" . $connection["dbname"] . "`"
206                         . " DEFAULT COLLATE '" . get_mysql_collation($connection["collation"]) . "'";
207
208                 if (!mysql_query($sql) || !mysql_select_db($connection["dbname"], $db))
209                                 return 0;
210         } else
211                 if (!db_set_collation($connection["collation"], $db))
212                         return 0;
213
214         return $db;
215 }
216
217 function db_drop_db($connection)
218 {
219
220         if ($connection["tbpref"] == "")
221         {
222                 $sql = "DROP DATABASE IF EXISTS " . $connection["dbname"] . "";
223                 return mysql_query($sql);
224         }
225         else
226         {
227         $res = db_query("show table status");
228         $all_tables = array();
229         while($row = db_fetch($res))
230                 $all_tables[] = $row;
231         // get table structures
232                 foreach ($all_tables as $table)
233                 {
234                         if (strpos($table['Name'], $connection["tbpref"]) === 0)
235                                 db_query("DROP TABLE `".$table['Name'] . "`");
236                 }
237                 //deleting the tables, how??
238                 return true;
239         }
240 }
241
242 function db_close($dbase = null)
243 {
244         global $db;
245         
246         if (!$dbase)
247                 $dbase = $db;
248         return mysql_close($dbase);
249 }
250
251 function db_extension_exists()
252 {
253         return function_exists('mysql_connect');
254 }
255
256 function db_escape_function($string)
257 {
258         return (function_exists('mysql_real_escape_string') ? mysql_real_escape_string($string) : mysql_escape_string($string));
259 }
260
261 /*
262         Set mysql client encoding.
263         Default is is encoding used by default language.
264 */
265 function db_set_encoding($ui_encoding=null)
266 {
267         global $dflt_lang, $installed_languages;
268
269         if (!isset($ui_encoding))
270         {
271                 $lang = array_search_value($dflt_lang, $installed_languages, 'code');
272                 $ui_encoding = strtoupper($lang['encoding']);
273         }
274
275         if ($mysql_enc = get_mysql_encoding_name($ui_encoding))
276                 mysql_set_charset($mysql_enc);
277 }
278
279 function db_get_charset($db)
280 {
281         return mysql_client_encoding();
282 }
283
284 function db_set_charset($db, $charset)
285 {
286         return mysql_set_charset($charset, $db);
287 }