forked from LibreHealthIO/lh-ehr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsql.inc
697 lines (632 loc) · 20.3 KB
/
sql.inc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
<?php
/**
* Sql functions/classes for LibreHealth EHR.
*
* Includes classes and functions that LibreHealth EHR uses
* to interact with SQL.
*
* LICENSE: This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>.
*
* @package LibreHealth EHR
* @link http://librehealth.io
*/
require_once(dirname(__FILE__) . "/sqlconf.php");
require_once(dirname(__FILE__) . "/adodb/adodb.inc.php");
require_once(dirname(__FILE__) . "/adodb/drivers/adodb-mysqli.inc.php");
require_once(dirname(__FILE__) . "/log.inc");
/**
* ADODB_mysql class wrapper to ensure proper auditing in LibreEHR.
*
* @author Kevin Yeh <[email protected]>
*/
class ADODB_mysqli_log extends ADODB_mysqli
{
/**
* ADODB Execute function wrapper to ensure proper auditing in LibreEHR.
*
* @param string $sql query
* @param array $inputarr binded variables array (optional)
* @return boolean returns false if error
*/
function Execute($sql,$inputarr=false)
{
$retval= parent::Execute($sql,$inputarr);
if ($retval === false) {
$outcome = false;
// Stash the error into last_mysql_error so it doesn't get clobbered when
// we insert into the audit log.
$GLOBALS['last_mysql_error']=$this->ErrorMsg();
// Last error no
$GLOBALS['last_mysql_error_no']=$this->ErrorNo();
}
else {
$outcome = true;
}
// Stash the insert ID into lastidado so it doesn't get clobbered when
// we insert into the audit log.
$GLOBALS['lastidado']=$this->Insert_ID();
auditSQLEvent($sql,$outcome,$inputarr);
return $retval;
}
/**
* ADODB Execute function wrapper to skip auditing in LibreEHR.
*
* Bypasses the LibreEHR auditing engine.
*
* @param string $sql query
* @param array $inputarr binded variables array (optional)
* @return boolean returns false if error
*/
function ExecuteNoLog($sql,$inputarr=false)
{
return parent::Execute($sql,$inputarr);
}
/*
* ADODB GenID function wrapper to work with LibreEHR.
*
* Need to override to fix a bug where call to GenID was updating
* sequences table but always returning a zero with the LibreEHR audit
* engine both on and off. Note this bug only appears to occur in recent
* php versions on windows. The fix is to use the ExecuteNoLog() function
* rather than the Execute() functions within this function (otherwise,
* there are no other changes from the original ADODB GenID function).
*
* @param string $seqname table name containing sequence (default is adodbseq)
* @param integer $startID id to start with for a new sequence (default is 1)
* @return integer returns the sequence integer
*/
function GenID($seqname='adodbseq',$startID=1)
{
// post-nuke sets hasGenID to false
if (!$this->hasGenID) return false;
$getnext = sprintf($this->_genIDSQL,$seqname);
$holdtransOK = $this->_transOK; // save the current status
$rs = @$this->ExecuteNoLog($getnext);
if (!$rs) {
if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset
$u = strtoupper($seqname);
$this->ExecuteNoLog(sprintf($this->_genSeqSQL,$seqname));
$cnt = $this->GetOne(sprintf($this->_genSeqCountSQL,$seqname));
if (!$cnt) $this->ExecuteNoLog(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
$rs = $this->ExecuteNoLog($getnext);
}
if ($rs) {
$this->genID = mysqli_insert_id($this->_connectionID);
$rs->Close();
} else
$this->genID = 0;
return $this->genID;
}
}
if (!defined('ADODB_FETCH_ASSOC')) define('ADODB_FETCH_ASSOC', 2);
$database = NewADOConnection("mysqli_log"); // Use the subclassed driver which logs execute events
// Below clientFlags flag is telling the mysql connection to allow local_infile setting,
// which is needed to import data in the Administration->Other->External Data Loads feature.
// Note this is a specific bug to work in Ubuntu 12.04, of which the Data Load feature does not
// work and is suspicious for a bug in PHP of that OS; Setting this clientFlags fixes this bug
// and appears to not cause problems in other operating systems.
$database->clientFlags = 128;
$database->port = $port;
$database->PConnect($host, $login, $pass, $dbase);
$GLOBALS['adodb']['db'] = $database;
$GLOBALS['dbh'] = $database->_connectionID;
// Modified 5/2009 by BM for UTF-8 project ---------
if (!$disable_utf8_flag) {
$success_flag = $database->Execute("SET NAMES 'utf8'");
if (!$success_flag) {
error_log("PHP custom error: from librehealth ehr library/sql.inc - Unable to set up UTF8 encoding with mysql database: ".getSqlLastError(), 0);
}
}
// Turn off STRICT SQL
$sql_strict_set_success = $database->Execute("SET sql_mode = ''");
if (!$sql_strict_set_success) {
error_log("Unable to set strict sql setting: ".getSqlLastError(), 0);
}
// set up associations in adodb calls (not sure why above define
// command does not work)
$GLOBALS['adodb']['db']->SetFetchMode(ADODB_FETCH_ASSOC);
//fmg: This makes the login screen informative when no connection can be made
if (!$GLOBALS['dbh']) {
//try to be more helpful
if ($host == "localhost") {
echo "Check that mysqld is running.<p>";
} else {
echo "Check that you can ping the server '".text($host)."'.<p>";
}//if local
HelpfulDie("Could not connect to server!", getSqlLastError());
exit;
}//if no connection
/**
* Standard sql query in LibreEHR.
*
* Function that will allow use of the adodb binding
* feature to prevent sql-injection. Will continue to
* be compatible with previous function calls that do
* not use binding.
* It will return a recordset object.
* The sqlFetchArray() function should be used to
* utilize the return object.
*
* @param string $statement query
* @param array $binds binded variables array (optional)
* @return recordset
*/
function sqlStatement($statement, $binds=false )
{
// Below line is to avoid a nasty bug in windows.
if (empty($binds)) $binds = false;
// Use adodb Execute with binding and return a recordset.
// Note that the auditSQLEvent function is embedded
// in the Execute command.
$recordset = $GLOBALS['adodb']['db']->Execute( $statement, $binds );
if ($recordset === FALSE) {
HelpfulDie("query failed: $statement", getSqlLastError());
}
return $recordset;
}
/**
* Specialized sql query in LibreEHR that skips auditing.
*
* Function that will allow use of the adodb binding
* feature to prevent sql-injection. Will continue to
* be compatible with previous function calls that do
* not use binding. It is equivalent to the
* sqlStatement() function, EXCEPT it skips the
* audit engine. This function should only be used
* in very special situations.
* It will return a recordset object.
* The sqlFetchArray() function should be used to
* utilize the return object.
*
* @param string $statement query
* @param array $binds binded variables array (optional)
* @return recordset
*/
function sqlStatementNoLog($statement, $binds=false )
{
// Below line is to avoid a nasty bug in windows.
if (empty($binds)) $binds = false;
// Use adodb ExecuteNoLog with binding and return a recordset.
$recordset = $GLOBALS['adodb']['db']->ExecuteNoLog( $statement, $binds );
if ($recordset === FALSE) {
HelpfulDie("query failed: $statement", getSqlLastError());
}
return $recordset;
}
/**
* sqlStatement() function wrapper for CDR engine in LibreEHR.
* Allows option to turn on/off auditing specifically for the
* CDR engine.
*
* @param string $statement query
* @param array $binds binded variables array (optional)
* @return recordset/resource
*/
function sqlStatementCdrEngine($statement, $binds=false )
{
// Below line is to avoid a nasty bug in windows.
if (empty($binds)) $binds = false;
if ($GLOBALS['audit_events_cdr']) {
return sqlStatement($statement,$binds);
}
else {
return sqlStatementNoLog($statement,$binds);
}
}
/**
* Returns a row (as an array) from a sql recordset.
*
* Function that will allow use of the adodb binding
* feature to prevent sql-injection.
* It will act upon the object returned from the
* sqlStatement() function (and sqlQ() function).
*
* @param recordset $r
* @return array
*/
function sqlFetchArray($r)
{
//treat as an adodb recordset
if ($r === FALSE)
return false;
if ($r->EOF)
return false;
//ensure it's an object (ie. is set)
if (!is_object($r))
return false;
return $r->FetchRow();
}
/**
* Wrapper for ADODB getAssoc
*
* @see http://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:getassoc
*
* @param string $sql
* @param string[] $bindvars
* @param boolean $forceArray
* @param boolean $first2Cols
* @return array
*/
function sqlGetAssoc( $sql, $bindvars=false, $forceArray=false, $first2Cols=false ) {
return $GLOBALS['adodb']['db']->getAssoc( $sql, $bindvars, $forceArray, $first2Cols );
}
/**
* Standard sql insert query in OpenEMR.
*
* Function that will allow use of the adodb binding
* feature to prevent sql-injection. This function
* is specialized for insert function and will return
* the last id generated from the insert.
*
* @param string $statement query
* @param array $binds binded variables array (optional)
* @return integer Last id generated from the sql insert command
*/
function sqlInsert($statement, $binds=false)
{
// Below line is to avoid a nasty bug in windows.
if (empty($binds)) $binds = false;
//Run a adodb execute
// Note the auditSQLEvent function is embedded in the
// Execute function.
$recordset = $GLOBALS['adodb']['db']->Execute($statement, $binds);
if ($recordset === FALSE) {
HelpfulDie("insert failed: $statement", getSqlLastError());
}
// Return the correct last id generated using function
// that is safe with the audit engine.
return getSqlLastID();
}
/**
* Specialized sql query in LibreEHR that only returns
* the first row of query results as an associative array.
*
* Function that will allow use of the adodb binding
* feature to prevent sql-injection.
*
* @param string $statement query
* @param array $binds binded variables array (optional)
* @return array
*/
function sqlQuery($statement, $binds=false)
{
// Below line is to avoid a nasty bug in windows.
if (empty($binds)) $binds = false;
$recordset = $GLOBALS['adodb']['db']->Execute( $statement, $binds );
if ($recordset === FALSE) {
HelpfulDie("query failed: $statement", getSqlLastError());
}
if ($recordset->EOF)
return FALSE;
$rez = $recordset->FetchRow();
if ($rez == FALSE)
return FALSE;
return $rez;
}
/**
* Specialized sql query in LibreEHR that bypasses the auditing engine
* and only returns the first row of query results as an associative array.
*
* Function that will allow use of the adodb binding
* feature to prevent sql-injection. It is equivalent to the
* sqlQuery() function, EXCEPT it skips the
* audit engine. This function should only be used
* in very special situations.
*
* @param string $statement query
* @param array $binds binded variables array (optional)
* @return array
*/
function sqlQueryNoLog($statement, $binds=false)
{
// Below line is to avoid a nasty bug in windows.
if (empty($binds)) $binds = false;
$recordset = $GLOBALS['adodb']['db']->ExecuteNoLog( $statement, $binds );
if ($recordset === FALSE) {
HelpfulDie("query failed: $statement", getSqlLastError());
}
if ($recordset->EOF)
return FALSE;
$rez = $recordset->FetchRow();
if ($rez == FALSE)
return FALSE;
return $rez;
}
/**
* Specialized sql query in LibreEHR that ignores sql errors, bypasses the
* auditing engine and only returns the first row of query results as an
* associative array.
*
* Function that will allow use of the adodb binding
* feature to prevent sql-injection. It is equivalent to the
* sqlQuery() function, EXCEPT it skips the
* audit engine and ignores erros. This function should only be used
* in very special situations.
*
* @param string $statement query
* @param array $binds binded variables array (optional)
* @return array
*/
function sqlQueryNoLogIgnoreError($statement, $binds=false)
{
// Below line is to avoid a nasty bug in windows.
if (empty($binds)) $binds = false;
$recordset = $GLOBALS['adodb']['db']->ExecuteNoLog( $statement, $binds );
if ($recordset === FALSE) {
// ignore the error and return FALSE
return FALSE;
}
if ($recordset->EOF)
return FALSE;
$rez = $recordset->FetchRow();
if ($rez == FALSE)
return FALSE;
return $rez;
}
/**
* sqlQuery() function wrapper for CDR engine in LibreEHR.
* Allows option to turn on/off auditing specifically for the
* CDR engine.
*
* @param string $statement query
* @param array $binds binded variables array (optional)
* @return array
*/
function sqlQueryCdrEngine($statement, $binds=false )
{
// Below line is to avoid a nasty bug in windows.
if (empty($binds)) $binds = false;
if ($GLOBALS['audit_events_cdr']) {
return sqlQuery($statement,$binds);
}
else {
return sqlQueryNoLog($statement,$binds);
}
}
/**
* Specialized sql query in LibreEHR that skips auditing.
*
* This function should only be used in very special situations.
*
* @param string $statement query
*/
function sqlInsertClean_audit($statement)
{
$ret = $GLOBALS['adodb']['db']->ExecuteNoLog($statement);
if ($ret === FALSE) {
HelpfulDie("insert failed: $statement", getSqlLastError());
}
}
/**
* Function that will safely return the last ID inserted,
* and accounts for the audit engine.
*
* @return integer Last ID that was inserted into sql
*/
function getSqlLastID() {
return $GLOBALS['lastidado'] > 0 ? $GLOBALS['lastidado'] : $GLOBALS['adodb']['db']->Insert_ID();
}
/**
* Function that will safely return the last error,
* and accounts for the audit engine.
*
* @param string $mode either adodb(default) or native_mysql
* @return string last mysql error
*/
function getSqlLastError() {
return !empty($GLOBALS['last_mysql_error']) ? $GLOBALS['last_mysql_error'] : $GLOBALS['adodb']['db']->ErrorMsg();
}
/**
* Function that will safely return the last error no,
* and accounts for the audit engine.
*
* @param string $mode either adodb(default) or native_mysql
* @return string last mysql error no
*/
function getSqlLastErrorNo() {
return !empty($GLOBALS['last_mysql_error_no']) ? $GLOBALS['last_mysql_error_no'] : $GLOBALS['adodb']['db']->ErrorNo();
}
/**
* Function that will return an array listing
* of columns that exist in a table.
*
* @param string $table sql table
* @return array
*/
function sqlListFields($table) {
$sql = "SHOW COLUMNS FROM ". add_escape_custom($table);
$resource = sqlQ($sql);
$field_list = array();
while($row = sqlFetchArray($resource)) {
$field_list[] = $row['Field'];
}
return $field_list;
}
/**
* Returns the number of sql rows
*
* @param recordset $r
* @return integer Number of rows
*/
function sqlNumRows($r)
{
return $r->RecordCount();
}
/**
* Error function for LibreEHR sql functions
*
* @param string $statement
* @param string $sqlerr
*/
function HelpfulDie ($statement, $sqlerr='')
{
echo "<p><p><font color='red'>ERROR:</font> ".text($statement)."<p>";
$logMsg="SQL Error with statement:".$statement;
if ($sqlerr) {
echo "Error: <font color='red'>".text($sqlerr)."</font><p>";
$logMsg.="--".$sqlerr;
}//if error
$backtrace=debug_backtrace();
for($level=1;$level<count($backtrace);$level++)
{
$info=$backtrace[$level];
echo "<br>".text($info["file"]." at ".$info["line"].":".$info["function"]);
if($level>1){
echo "(".text(implode(",",$info["args"])).")";
}
}
$logMsg.="==>".$backtrace[1]["file"]." at ".$backtrace[1]["line"].":".$backtrace[1]["function"];
error_log($logMsg);
exit;
}
/**
* @todo document use of the generate_id function
*/
function generate_id () {
$database = $GLOBALS['adodb']['db'];
return $database->GenID("sequences");
}
/**
* Deprecated function. Standard sql query in LibreEHR.
*
* Function that will allow use of the adodb binding
* feature to prevent sql-injection. Will continue to
* be compatible with previous function calls that do
* not use binding.
* It will return a recordset object.
* The sqlFetchArray() function should be used to
* utilize the return object.
*
* @deprecated
* @param string $statement query
* @param array $binds binded variables array (optional)
* @return recordset
*/
function sqlQ($statement, $binds=false )
{
// Below line is to avoid a nasty bug in windows.
if (empty($binds)) $binds = false;
$recordset = $GLOBALS['adodb']['db']->Execute( $statement, $binds ) or
HelpfulDie("query failed: $statement", getSqlLastError());
return $recordset;
}
/**
* Simple wrapper for sqlInsert() function (deprecated).
*
* Function that will allow use of the adodb binding feature
* to prevent sql-injection.
*
* @deprecated
* @param string $statement query
* @param array $binds binded variables array (optional)
* @return integer Last id generated from the sql insert command
*/
function idSqlStatement($statement , $binds=false )
{
// Below line is to avoid a nasty bug in windows.
if (empty($binds)) $binds = false;
return sqlInsert($statement, $binds);
}
/**
* Simple wrapper for sqlInsert() function (deprecated).
*
* Function that will allow use of the adodb binding feature
* to prevent sql-injection.
*
* @deprecated
* @param string $statement query
* @param array $binds binded variables array (optional)
* @return integer Last id generated from the sql insert command
*/
function sqlInsertClean($statement, $binds=false )
{
// Below line is to avoid a nasty bug in windows.
if (empty($binds)) $binds = false;
return sqlInsert($statement, $binds);
}
/**
* Sql close connection function (deprecated)
*
* No longer needed since PHP does this automatically.
*
* @deprecated
* @return boolean
*/
function sqlClose()
{
//----------Close our mysql connection
$closed = $GLOBALS['adodb']['db']->close or
HelpfulDie("could not disconnect from mysql server link", getSqlLastError());
return $closed;
}
/**
* Very simple wrapper function and not necessary (deprecated)
*
* Do not use.
*
* @deprecated
* @return connection
*/
function get_db() {
return $GLOBALS['adodb']['db'];
}
/**
* Generic mysql select db function
* Used when converted to mysqli to centralize special circumstances.
* @param string $database
*/
function generic_sql_select_db($database, $link = null)
{
if (is_null($link))
$link = $GLOBALS['dbh'];
mysqli_select_db($link, $database);
}
/**
* Generic mysql affected rows function
* Used when converted to mysqli to centralize special circumstances.
*
*/
function generic_sql_affected_rows()
{
return mysqli_affected_rows($GLOBALS['dbh']);
}
/**
* Generic mysql insert id function
* Used when converted to mysqli to centralize special circumstances.
*
*/
function generic_sql_insert_id()
{
return mysqli_insert_id($GLOBALS['dbh']);
}
/**
* Begin a Transaction.
*/
function sqlBeginTrans()
{
$GLOBALS['adodb']['db']->BeginTrans();
}
/**
* Commit a transaction
*/
function sqlCommitTrans($ok=true)
{
$GLOBALS['adodb']['db']->CommitTrans();
}
/**
* Rollback a transaction
*/
function sqlRollbackTrans()
{
$GLOBALS['adodb']['db']->RollbackTrans();
}
?>