added ability to not show sql query errors (#877)
[openemr.git] / library / sql.inc
blob75dbbc20f2004eb548ca8c25d1b770d65e50b910
1 <?php
2 /**
3 * Sql functions/classes for OpenEMR.
5 * Includes classes and functions that OpenEMR uses
6 * to interact with SQL.
8 * LICENSE: This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program.  If not, see <http://opensource.org/licenses/gpl-license.php>.
19 * @package   OpenEMR
20 * @link      http://www.open-emr.org
23 require_once(dirname(__FILE__) . "/sqlconf.php");
24 require_once(dirname(__FILE__) . "/../vendor/adodb/adodb-php/adodb.inc.php");
25 require_once(dirname(__FILE__) . "/../vendor/adodb/adodb-php/drivers/adodb-mysqli.inc.php");
26 require_once(dirname(__FILE__) . "/log.inc");
28 /**
29 * ADODB_mysql class wrapper to ensure proper auditing in OpenEMR.
31 * @author  Kevin Yeh <kevin.y@integralemr.com>
33 class ADODB_mysqli_log extends ADODB_mysqli
35         /**
36         * ADODB Execute function wrapper to ensure proper auditing in OpenEMR.
37         *
38         * @param  string  $sql         query
39         * @param  array   $inputarr    binded variables array (optional)
40         * @return boolean              returns false if error
41         */
42         function Execute($sql,$inputarr=false)
43         {
44             $retval= parent::Execute($sql,$inputarr);
45             if ($retval === false) {
46               $outcome = false;
47               // Stash the error into last_mysql_error so it doesn't get clobbered when
48               // we insert into the audit log.
49               $GLOBALS['last_mysql_error']=$this->ErrorMsg();
51               // Last error no
52               $GLOBALS['last_mysql_error_no']=$this->ErrorNo();
53             }
54             else {
55               $outcome = true;
56             }
57             // Stash the insert ID into lastidado so it doesn't get clobbered when
58             // we insert into the audit log.
59             $GLOBALS['lastidado']=$this->Insert_ID();
60             auditSQLEvent($sql,$outcome,$inputarr);
61             return $retval;
62         }
64         /**
65         * ADODB Execute function wrapper to skip auditing in OpenEMR.
66         *
67         * Bypasses the OpenEMR auditing engine.
68         *
69         * @param  string  $sql         query
70         * @param  array   $inputarr    binded variables array (optional)
71         * @return boolean              returns false if error
72         */
73         function ExecuteNoLog($sql,$inputarr=false)
74         {
75             return parent::Execute($sql,$inputarr);
76         }
78         /*
79         * ADODB GenID function wrapper to work with OpenEMR.
80         *
81         * Need to override to fix a bug where call to GenID was updating
82         * sequences table but always returning a zero with the OpenEMR audit
83         * engine both on and off. Note this bug only appears to occur in recent
84         * php versions on windows. The fix is to use the ExecuteNoLog() function
85         * rather than the Execute() functions within this function (otherwise,
86         * there are no other changes from the original ADODB GenID function).
87         *
88         * @param  string  $seqname     table name containing sequence (default is adodbseq)
89         * @param  integer $startID     id to start with for a new sequence (default is 1)
90         * @return integer              returns the sequence integer
91         */
92         function GenID($seqname='adodbseq',$startID=1)
93         {
94                 // post-nuke sets hasGenID to false
95                 if (!$this->hasGenID) return false;
97                 $getnext = sprintf($this->_genIDSQL,$seqname);
98                 $holdtransOK = $this->_transOK; // save the current status
99                 $rs = @$this->ExecuteNoLog($getnext);
100                 if (!$rs) {
101                         if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset
102                         $u = strtoupper($seqname);
103                         $this->ExecuteNoLog(sprintf($this->_genSeqSQL,$seqname));
104                         $cnt = $this->GetOne(sprintf($this->_genSeqCountSQL,$seqname));
105                         if (!$cnt) $this->ExecuteNoLog(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
106                         $rs = $this->ExecuteNoLog($getnext);
107                 }
109                 if ($rs) {
110                         $this->genID = mysqli_insert_id($this->_connectionID);
111                         $rs->Close();
112                 } else
113                         $this->genID = 0;
115                 return $this->genID;
116         }
118 if (!defined('ADODB_FETCH_ASSOC')) define('ADODB_FETCH_ASSOC', 2);
119 $database = NewADOConnection("mysqli_log"); // Use the subclassed driver which logs execute events
120 // Below clientFlags flag is telling the mysql connection to allow local_infile setting,
121 // which is needed to import data in the Administration->Other->External Data Loads feature.
122 // Note this is a specific bug to work in Ubuntu 12.04, of which the Data Load feature does not
123 // work and is suspicious for a bug in PHP of that OS; Setting this clientFlags fixes this bug
124 // and appears to not cause problems in other operating systems.
125 $database->clientFlags = 128;
126 $database->port = $port;
127 $database->PConnect($host, $login, $pass, $dbase);
128 $GLOBALS['adodb']['db'] = $database;
129 $GLOBALS['dbh'] = $database->_connectionID;
131 // Modified 5/2009 by BM for UTF-8 project ---------
132 if (!$disable_utf8_flag) {
133  $success_flag = $database->Execute("SET NAMES 'utf8'");
134   if (!$success_flag) {
135    error_log("PHP custom error: from openemr library/sql.inc  - Unable to set up UTF8 encoding with mysql database: ".getSqlLastError(), 0);
136   }
139 // Turn off STRICT SQL
140 $sql_strict_set_success = $database->Execute("SET sql_mode = ''");
141 if (!$sql_strict_set_success) {
142  error_log("Unable to set strict sql setting: ".getSqlLastError(), 0);
145 // set up associations in adodb calls (not sure why above define
146 //  command does not work)
147 $GLOBALS['adodb']['db']->SetFetchMode(ADODB_FETCH_ASSOC);
149 //fmg: This makes the login screen informative when no connection can be made
150 if (!$GLOBALS['dbh']) {
151   //try to be more helpful
152   if ($host == "localhost") {
153     echo "Check that mysqld is running.<p>";
154   } else {
155     echo "Check that you can ping the server " . text($host) . ".<p>";
156   }//if local
157   HelpfulDie("Could not connect to server!", getSqlLastError());
158   exit;
159 }//if no connection
162 * Standard sql query in OpenEMR.
164 * Function that will allow use of the adodb binding
165 * feature to prevent sql-injection. Will continue to
166 * be compatible with previous function calls that do
167 * not use binding.
168 * It will return a recordset object.
169 * The sqlFetchArray() function should be used to
170 * utilize the return object.
172 * @param  string  $statement  query
173 * @param  array   $binds      binded variables array (optional)
174 * @return recordset
176 function sqlStatement($statement, $binds=false )
178   // Below line is to avoid a nasty bug in windows.
179   if (empty($binds)) $binds = false;
181   // Use adodb Execute with binding and return a recordset.
182   //   Note that the auditSQLEvent function is embedded
183   //    in the Execute command.
184   $recordset = $GLOBALS['adodb']['db']->Execute( $statement, $binds );
185   if ($recordset === FALSE) {
186     HelpfulDie("query failed: $statement", getSqlLastError());
187   }
188   return $recordset;
192 * Specialized sql query in OpenEMR that skips auditing.
194 * Function that will allow use of the adodb binding
195 * feature to prevent sql-injection. Will continue to
196 * be compatible with previous function calls that do
197 * not use binding. It is equivalent to the
198 * sqlStatement() function, EXCEPT it skips the
199 * audit engine. This function should only be used
200 * in very special situations.
201 * It will return a recordset object.
202 * The sqlFetchArray() function should be used to
203 * utilize the return object.
205 * @param  string  $statement  query
206 * @param  array   $binds      binded variables array (optional)
207 * @return recordset
209 function sqlStatementNoLog($statement, $binds=false )
211   // Below line is to avoid a nasty bug in windows.
212   if (empty($binds)) $binds = false;
214   // Use adodb ExecuteNoLog with binding and return a recordset.
215   $recordset = $GLOBALS['adodb']['db']->ExecuteNoLog( $statement, $binds );
216   if ($recordset === FALSE) {
217     HelpfulDie("query failed: $statement", getSqlLastError());
218   }
219   return $recordset;
223 * sqlStatement() function wrapper for CDR engine in OpenEMR.
224 * Allows option to turn on/off auditing specifically for the
225 * CDR engine.
227 * @param  string  $statement  query
228 * @param  array   $binds      binded variables array (optional)
229 * @return recordset/resource
231 function sqlStatementCdrEngine($statement, $binds=false )
233   // Below line is to avoid a nasty bug in windows.
234   if (empty($binds)) $binds = false;
236   if ($GLOBALS['audit_events_cdr']) {
237     return sqlStatement($statement,$binds);
238   }
239   else {
240     return sqlStatementNoLog($statement,$binds);
241   }
245 * Returns a row (as an array) from a sql recordset.
247 * Function that will allow use of the adodb binding
248 * feature to prevent sql-injection.
249 * It will act upon the object returned from the
250 * sqlStatement() function (and sqlQ() function).
252 * @param recordset $r
253 * @return array
255 function sqlFetchArray($r)
257   //treat as an adodb recordset
258   if ($r === FALSE)
259     return false;
260   if ($r->EOF)
261     return false;
262   //ensure it's an object (ie. is set)
263   if (!is_object($r))
264     return false;
266     return $r->FetchRow();
271  * Wrapper for ADODB getAssoc
273  * @see http://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:getassoc
275  * @param string $sql
276  * @param string[] $bindvars
277  * @param boolean $forceArray
278  * @param boolean $first2Cols
279  * @return array
280  */
281 function sqlGetAssoc( $sql, $bindvars=false, $forceArray=false, $first2Cols=false ) {
283   return $GLOBALS['adodb']['db']->getAssoc( $sql, $bindvars, $forceArray, $first2Cols  );
288 * Standard sql insert query in OpenEMR.
290 * Function that will allow use of the adodb binding
291 * feature to prevent sql-injection. This function
292 * is specialized for insert function and will return
293 * the last id generated from the insert.
295 * @param  string   $statement  query
296 * @param  array    $binds      binded variables array (optional)
297 * @return integer  Last id generated from the sql insert command
299 function sqlInsert($statement, $binds=false)
301   // Below line is to avoid a nasty bug in windows.
302   if (empty($binds)) $binds = false;
304   //Run a adodb execute
305   // Note the auditSQLEvent function is embedded in the
306   //   Execute function.
307   $recordset = $GLOBALS['adodb']['db']->Execute($statement, $binds);
308   if ($recordset === FALSE) {
309     HelpfulDie("insert failed: $statement", getSqlLastError());
310   }
311   // Return the correct last id generated using function
312   //   that is safe with the audit engine.
313   return getSqlLastID();
317 * Specialized sql query in OpenEMR that only returns
318 * the first row of query results as an associative array.
320 * Function that will allow use of the adodb binding
321 * feature to prevent sql-injection.
323 * @param  string  $statement  query
324 * @param  array   $binds      binded variables array (optional)
325 * @return array
327 function sqlQuery($statement, $binds=false)
329   // Below line is to avoid a nasty bug in windows.
330   if (empty($binds)) $binds = false;
332   $recordset = $GLOBALS['adodb']['db']->Execute( $statement, $binds );
334   if ($recordset === FALSE) {
335     HelpfulDie("query failed: $statement", getSqlLastError());
336   }
337   if ($recordset->EOF)
338    return FALSE;
339   $rez = $recordset->FetchRow();
340   if ($rez == FALSE)
341     return FALSE;
342   return $rez;
346 * Specialized sql query in OpenEMR that bypasses the auditing engine
347 * and only returns the first row of query results as an associative array.
349 * Function that will allow use of the adodb binding
350 * feature to prevent sql-injection. It is equivalent to the
351 * sqlQuery() function, EXCEPT it skips the
352 * audit engine. This function should only be used
353 * in very special situations.
355 * @param  string  $statement  query
356 * @param  array   $binds      binded variables array (optional)
357 * @return array
359 function sqlQueryNoLog($statement, $binds=false)
361   // Below line is to avoid a nasty bug in windows.
362   if (empty($binds)) $binds = false;
364   $recordset = $GLOBALS['adodb']['db']->ExecuteNoLog( $statement, $binds );
366   if ($recordset === FALSE) {
367     HelpfulDie("query failed: $statement", getSqlLastError());
368   }
369   if ($recordset->EOF)
370    return FALSE;
371   $rez = $recordset->FetchRow();
372   if ($rez == FALSE)
373     return FALSE;
374   return $rez;
378 * Specialized sql query in OpenEMR that ignores sql errors, bypasses the
379 * auditing engine and only returns the first row of query results as an
380 * associative array.
382 * Function that will allow use of the adodb binding
383 * feature to prevent sql-injection. It is equivalent to the
384 * sqlQuery() function, EXCEPT it skips the
385 * audit engine and ignores erros. This function should only be used
386 * in very special situations.
388 * @param  string  $statement  query
389 * @param  array   $binds      binded variables array (optional)
390 * @return array
392 function sqlQueryNoLogIgnoreError($statement, $binds=false)
394   // Below line is to avoid a nasty bug in windows.
395   if (empty($binds)) $binds = false;
397   $recordset = $GLOBALS['adodb']['db']->ExecuteNoLog( $statement, $binds );
399   if ($recordset === FALSE) {
400     // ignore the error and return FALSE
401     return FALSE;
402   }
403   if ($recordset->EOF)
404    return FALSE;
405   $rez = $recordset->FetchRow();
406   if ($rez == FALSE)
407     return FALSE;
408   return $rez;
412 * sqlQuery() function wrapper for CDR engine in OpenEMR.
413 * Allows option to turn on/off auditing specifically for the
414 * CDR engine.
416 * @param  string  $statement  query
417 * @param  array   $binds      binded variables array (optional)
418 * @return array
420 function sqlQueryCdrEngine($statement, $binds=false )
422   // Below line is to avoid a nasty bug in windows.
423   if (empty($binds)) $binds = false;
425   if ($GLOBALS['audit_events_cdr']) {
426     return sqlQuery($statement,$binds);
427   }
428   else {
429     return sqlQueryNoLog($statement,$binds);
430   }
434 * Specialized sql query in OpenEMR that skips auditing.
436 * This function should only be used in very special situations.
438 * @param  string  $statement  query
440 function sqlInsertClean_audit($statement)
443   $ret = $GLOBALS['adodb']['db']->ExecuteNoLog($statement);
444   if ($ret === FALSE) {
445     HelpfulDie("insert failed: $statement", getSqlLastError());
446   }
450 * Function that will safely return the last ID inserted,
451 * and accounts for the audit engine.
453 * @return  integer Last ID that was inserted into sql
455 function getSqlLastID() {
456     return $GLOBALS['lastidado'] > 0 ? $GLOBALS['lastidado'] : $GLOBALS['adodb']['db']->Insert_ID();
460 * Function that will safely return the last error,
461 * and accounts for the audit engine.
463 * @param   string  $mode either adodb(default) or native_mysql
464 * @return  string        last mysql error
466 function getSqlLastError() {
467     return !empty($GLOBALS['last_mysql_error']) ? $GLOBALS['last_mysql_error'] : $GLOBALS['adodb']['db']->ErrorMsg();
471  * Function that will safely return the last error no,
472  * and accounts for the audit engine.
474  * @param   string  $mode either adodb(default) or native_mysql
475  * @return  string        last mysql error no
476  */
477 function getSqlLastErrorNo() {
478     return !empty($GLOBALS['last_mysql_error_no']) ? $GLOBALS['last_mysql_error_no'] : $GLOBALS['adodb']['db']->ErrorNo();
482 * Function that will return an array listing
483 * of columns that exist in a table.
485 * @param   string  $table sql table
486 * @return  array
488 function sqlListFields($table) {
489   $sql = "SHOW COLUMNS FROM ". add_escape_custom($table);
490   $resource = sqlQ($sql);
491   $field_list = array();
492   while($row = sqlFetchArray($resource)) {
493     $field_list[] = $row['Field'];
494   }
495   return $field_list;
499 * Returns the number of sql rows
501 * @param recordset $r
502 * @return integer Number of rows
504 function sqlNumRows($r)
506   return $r->RecordCount();
510 * Error function for OpenEMR sql functions
512 * @param string $statement
513 * @param string $sqlerr
515 function HelpfulDie ($statement, $sqlerr='')
518   if($GLOBALS['sql_string_no_show_screen']){
519     echo "<h2>" . xlt('Save Unsuccessful.') . "</h2>";
520   }
521   else {
522     echo "<p><p><font color='red'>ERROR:</font> " . text($statement) . "<p>";
523   }
525   $logMsg="SQL Error with statement:".$statement;
527   if ($sqlerr) {
528     if(!$GLOBALS['sql_string_no_show_screen']) {
529        echo "Error: <font color='red'>" . text($sqlerr) . "</font><p>";
530     }
531     $logMsg.="--".$sqlerr;
532   }//if error
534   $backtrace = debug_backtrace();
536   if(!$GLOBALS['sql_string_no_show_screen']) {
537       for ($level = 1; $level < count($backtrace); $level++)
538       {
539           $info = $backtrace[$level];
540           echo "<br>" . text($info["file"] . " at " . $info["line"] . ":" . $info["function"]);
541           if ($level > 1) {
542               echo "(" . text(implode(",", $info["args"])) . ")";
543           }
544       }
545   }
547   $logMsg.="==>".$backtrace[1]["file"]." at ".$backtrace[1]["line"].":".$backtrace[1]["function"];
549   error_log($logMsg);
551   exit;
555 * @todo document use of the generate_id function
557 function generate_id () {
558   $database = $GLOBALS['adodb']['db'];
559   return $database->GenID("sequences");
563 * Deprecated function. Standard sql query in OpenEMR.
565 * Function that will allow use of the adodb binding
566 * feature to prevent sql-injection. Will continue to
567 * be compatible with previous function calls that do
568 * not use binding.
569 * It will return a recordset object.
570 * The sqlFetchArray() function should be used to
571 * utilize the return object.
573 * @deprecated
574 * @param  string  $statement  query
575 * @param  array   $binds      binded variables array (optional)
576 * @return recordset
578 function sqlQ($statement, $binds=false )
580   // Below line is to avoid a nasty bug in windows.
581   if (empty($binds)) $binds = false;
583   $recordset = $GLOBALS['adodb']['db']->Execute( $statement, $binds ) or
584     HelpfulDie("query failed: $statement", getSqlLastError());
585   return $recordset;
589 * Simple wrapper for sqlInsert() function (deprecated).
591 * Function that will allow use of the adodb binding feature
592 * to prevent sql-injection.
594 * @deprecated
595 * @param  string   $statement  query
596 * @param  array    $binds      binded variables array (optional)
597 * @return integer  Last id generated from the sql insert command
599 function idSqlStatement($statement , $binds=false )
601   // Below line is to avoid a nasty bug in windows.
602   if (empty($binds)) $binds = false;
604   return sqlInsert($statement, $binds);
608 * Simple wrapper for sqlInsert() function (deprecated).
610 * Function that will allow use of the adodb binding feature
611 * to prevent sql-injection.
613 * @deprecated
614 * @param  string   $statement  query
615 * @param  array    $binds      binded variables array (optional)
616 * @return integer  Last id generated from the sql insert command
618 function sqlInsertClean($statement, $binds=false )
620   // Below line is to avoid a nasty bug in windows.
621   if (empty($binds)) $binds = false;
623   return sqlInsert($statement, $binds);
628 * Sql close connection function (deprecated)
630 * No longer needed since PHP does this automatically.
632 * @deprecated
633 * @return boolean
635 function sqlClose()
637   //----------Close our mysql connection
638   $closed = $GLOBALS['adodb']['db']->close or
639     HelpfulDie("could not disconnect from mysql server link", getSqlLastError());
640   return $closed;
644 * Very simple wrapper function and not necessary (deprecated)
646 * Do not use.
648 * @deprecated
649 * @return connection
651 function get_db() {
652   return $GLOBALS['adodb']['db'];
656  * Generic mysql select db function
657  * Used when converted to mysqli to centralize special circumstances.
658  * @param string $database
659  */
660 function generic_sql_select_db($database, $link = null)
662   if (is_null($link))
663     $link = $GLOBALS['dbh'];
664   mysqli_select_db($link, $database);
668  * Generic mysql affected rows function
669  * Used when converted to mysqli to centralize special circumstances.
671  */
672 function generic_sql_affected_rows()
674   return mysqli_affected_rows($GLOBALS['dbh']);
678  * Generic mysql insert id function
679  * Used when converted to mysqli to centralize special circumstances.
681                                  */
682 function generic_sql_insert_id()
684   return mysqli_insert_id($GLOBALS['dbh']);
689  * Begin a Transaction.
690  */
691 function sqlBeginTrans()
693     $GLOBALS['adodb']['db']->BeginTrans();
698  * Commit a transaction
699  */
700 function sqlCommitTrans($ok=true)
702     $GLOBALS['adodb']['db']->CommitTrans();
707  * Rollback a transaction
708  */
709 function sqlRollbackTrans()
711     $GLOBALS['adodb']['db']->RollbackTrans();