1<?php
2/* Database abstraction for mysqli */
3
4define ('LIKE', 'LIKE');
5
6if(!isset($mysqlport)) {
7	$mysqlport = 3306;
8}
9global $db;	// Make sure it IS global, regardless of our context
10
11$db = mysqli_connect($host , $DBUser, $DBPassword,$_SESSION['DatabaseName'], $mysqlport);
12
13
14//this statement sets the charset to be used for sending data to and from the db server
15//if not set, both mysqli server and mysqli client/library may assume otherwise
16mysqli_set_charset($db, 'utf8');
17
18/* check connection */
19if(mysqli_connect_errno()) {
20	printf("Connect failed: %s\n", mysqli_connect_error());
21	session_unset();
22	session_destroy();
23	echo '<p>' . _('Click') . ' ' . '<a href="index.php">' . _('here') . '</a>' . ' ' ._('to try logging in again') . '</p>';
24	exit();
25}
26
27if(!$db) {
28	echo '<br />' . _('The configuration in the file config.php for the database user name and password do not provide the information required to connect to the database server');
29	exit;
30}
31
32/* Update to allow RecurringSalesOrdersProcess.php to run via cron */
33if(isset($DatabaseName)) {
34	if(!mysqli_select_db($db,$DatabaseName)) {
35		echo '<br />' . _('The company name entered does not correspond to a database on the database server specified in the config.php configuration file. Try logging in with a different company name');
36		echo '<br /><a href="index.php">' . _('Back to login page') . '</a>';
37		unset ($DatabaseName);
38		exit;
39	}
40} else {
41	if(!mysqli_select_db($db,$_SESSION['DatabaseName'])) {
42		echo '<br />' . _('The company name entered does not correspond to a database on the database server specified in the config.php configuration file. Try logging in with a different company name');
43		echo '<br /><a href="index.php">' . _('Back to login page') . '</a>';
44		unset ($_SESSION['DatabaseName']);
45		exit;
46	}
47}
48
49//DB wrapper functions to change only once for whole application
50
51function DB_query($SQL, $ErrorMessage='', $DebugMessage= '', $Transaction=false, $TrapErrors=true) {
52
53	global $debug;
54	global $PathPrefix;
55	global $db;
56	global $Messages;
57
58	$result = mysqli_query($db, $SQL);
59	$_SESSION['LastInsertId'] = mysqli_insert_id($db);
60
61	if($DebugMessage == '') {
62		$DebugMessage = _('The SQL that failed was');
63	}
64
65	if(DB_error_no() != 0 AND $TrapErrors==true) {
66		require_once($PathPrefix . 'includes/header.php');
67		prnMsg($ErrorMessage . '<br />' . DB_error_msg(), 'error', _('Database Error'). ' ' . DB_error_no());
68		if($debug==1) {
69			prnMsg($DebugMessage. '<br />' . $SQL . '<br />','error',_('Database SQL Failure'));
70		}
71		if($Transaction) {
72			$SQL = 'rollback';
73			$Result = DB_query($SQL);
74			if(DB_error_no() != 0) {
75				prnMsg(_('Error Rolling Back Transaction'), 'error', _('Database Rollback Error'). ' ' .DB_error_no() );
76			}else{
77				prnMsg(_('Rolling Back Transaction OK'), 'error', _('Database Rollback Due to Error Above'));
78			}
79		}
80		include($PathPrefix . 'includes/footer.php');
81		exit;
82	} elseif(isset($_SESSION['MonthsAuditTrail']) and (DB_error_no()==0 AND $_SESSION['MonthsAuditTrail']>0) AND (DB_affected_rows($result)>0)) {
83
84		$SQLArray = explode(' ', $SQL);
85
86		if(($SQLArray[0] == 'INSERT')
87			OR ($SQLArray[0] == 'UPDATE')
88			OR ($SQLArray[0] == 'DELETE')) {
89
90			if($SQLArray[2] != 'audittrail') { // to ensure the auto delete of audit trail history is not logged
91				$AuditSQL = "INSERT INTO audittrail (transactiondate,
92									userid,
93									querystring)
94						VALUES('" . Date('Y-m-d H:i:s') . "',
95							'" . trim($_SESSION['UserID']) . "',
96							'" . DB_escape_string($SQL) . "')";
97
98				$AuditResult = mysqli_query($db, $AuditSQL);
99			}
100		}
101	}
102
103	return $result;
104}
105
106function DB_fetch_row($ResultIndex) {
107	$RowPointer=mysqli_fetch_row($ResultIndex);
108	return $RowPointer;
109}
110
111function DB_fetch_assoc($ResultIndex) {
112	$RowPointer=mysqli_fetch_assoc($ResultIndex);
113	return $RowPointer;
114}
115
116function DB_fetch_array($ResultIndex) {
117	$RowPointer = mysqli_fetch_array($ResultIndex);
118	return $RowPointer;
119}
120
121function DB_data_seek(&$ResultIndex,$Record) {
122	mysqli_data_seek($ResultIndex,$Record);
123}
124
125function DB_free_result($ResultIndex) {
126	if(is_resource($ResultIndex)) {
127		mysqli_free_result($ResultIndex);
128	}
129}
130
131function DB_num_rows($ResultIndex) {
132	return mysqli_num_rows($ResultIndex);
133}
134
135function DB_affected_rows($ResultIndex) {
136	global $db;
137	return mysqli_affected_rows($db);
138}
139
140function DB_error_no() {
141	global $db;
142	return mysqli_errno($db);
143}
144
145function DB_error_msg() {
146	global $db;
147	return mysqli_error($db);
148}
149
150function DB_Last_Insert_ID($Table, $FieldName) {
151//	return mysqli_insert_id($Conn);
152	if(isset($_SESSION['LastInsertId'])) {
153		$Last_Insert_ID = $_SESSION['LastInsertId'];
154	} else {
155		$Last_Insert_ID = 0;
156	}
157//	unset($_SESSION['LastInsertId']);
158	return $Last_Insert_ID;
159}
160
161function DB_escape_string($String) {
162	global $db;
163	return mysqli_real_escape_string($db, $String);
164}
165
166function DB_show_tables() {
167	$Result = DB_query('SHOW TABLES');
168	return $Result;
169}
170
171function DB_show_fields($TableName) {
172	$Result = DB_query("DESCRIBE $TableName");
173	return $Result;
174}
175
176function interval( $val, $Inter ) {
177		return "\n".'interval ' . $val . ' ' . $Inter . "\n";
178}
179
180function DB_Maintenance() {
181	prnMsg(_('The system has just run the regular database administration and optimisation routine.'),'info');
182
183	$TablesResult = DB_show_tables();
184	while ($myrow = DB_fetch_row($TablesResult)) {
185		$Result = DB_query('OPTIMIZE TABLE ' . $myrow[0]);
186	}
187
188	$Result = DB_query("UPDATE config
189				SET confvalue = CURRENT_DATE
190				WHERE confname = 'DB_Maintenance_LastRun'");
191}
192
193function DB_Txn_Begin() {
194	global $db;
195	mysqli_query($db,'SET autocommit=0');
196	mysqli_query($db,'START TRANSACTION');
197}
198
199function DB_Txn_Commit() {
200	global $db;
201	mysqli_query($db,'COMMIT');
202	mysqli_query($db,'SET autocommit=1');
203}
204
205function DB_Txn_Rollback() {
206	global $db;
207	mysqli_query($db,'ROLLBACK');
208}
209
210function DB_IgnoreForeignKeys() {
211	global $db;
212	mysqli_query($db,'SET FOREIGN_KEY_CHECKS=0');
213}
214
215function DB_ReinstateForeignKeys() {
216	global $db;
217	mysqli_query($db, 'SET FOREIGN_KEY_CHECKS=1');
218}
219
220function DB_table_exists($TableName) {
221	global $db;
222
223	$SQL = "SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA = '" . $_SESSION['DatabaseName'] . "' AND TABLE_NAME = '" . $TableName . "'";
224	$Result = DB_query($SQL);
225
226	if (DB_num_rows($Result) > 0) {
227		return True;
228	} else {
229		return False;
230	}
231}
232?>
233