Migrated logging options from global.php to Administration => Globals.
[openemr.git] / library / log.inc
blobfcf8b03f1a693d019ee6235fa7604e4c9eab466c
1 <?php
2 #require_once("{$GLOBALS['srcdir']}/sql.inc");
3 require_once(dirname(__FILE__). "/sql.inc");
5 function newEvent($event, $user, $groupname, $success, $comments="") {
6     $adodb = $GLOBALS['adodb']['db'];
7     $crt_user=$_SERVER['SSL_CLIENT_S_DN_CN'];
8     /* More details added to the log */
9     $sql = "insert into log ( date, event, user, groupname, success, comments, crt_user) " .
10             "values ( NOW(), " . $adodb->qstr($event) . "," . $adodb->qstr($user) .
11             "," . $adodb->qstr($groupname) . "," . $adodb->qstr($success) . "," .
12             $adodb->qstr($comments) ."," .
13             $adodb->qstr($crt_user) .  ")";
14     //$ret = sqlInsertClean($sql);
15     // Call the new function created for audit log
16     $ret = sqlInsertClean_audit($sql);
17     send_atna_audit_msg($user, $groupname, $event, 0, $success, $comments);
20 function getEventByDate($date, $user="", $cols="DISTINCT date, event, user, groupname, patient_id, success, comments, checksum")
22     $sql = "SELECT $cols FROM log WHERE date >= '$date 00:00:00' AND date <= '$date 23:59:59'";
23     if ($user) $sql .= " AND user LIKE '$user'";
24     $sql .= " ORDER BY date DESC LIMIT 5000";
25     $res = sqlStatement($sql);
26     for($iter=0; $row=sqlFetchArray($res); $iter++) {
27         $all[$iter] = $row;
28     }
29     return $all;
32 /******************
33  * Get records from the LOG and Extended_Log table
34  * using the optional parameters:
35  *   date : a specific date  (defaults to today)
36  *   user : a specific user  (defaults to none)
37  *   cols : gather specific columns  (defaults to date,event,user,groupname,comments)
38  *   sortby : sort the results by  (defaults to none)
39  * RETURNS:
40  *   array of results
41  ******************/
42 function getEvents($params) 
44     // parse the parameters
45     $cols = "DISTINCT date, event, user, groupname, patient_id, success, comments,checksum,crt_user";
46     if (isset($params['cols']) && $params['cols'] != "") $cols = $params['cols'];
48     $date1 = date("Y-m-d", time());
49     if (isset($params['sdate']) && $params['sdate'] != "") $date1= $params['sdate'];
50     
51     $date2 = date("Y-m-d", time());
52     if (isset($params['edate']) && $params['edate'] != "") $date2= $params['edate'];
53     
54     $user = "";
55     if (isset($params['user']) && $params['user'] != "") $user= $params['user'];
57     //VicarePlus :: For Generating log with patient id.
58     $patient = "";
59     if (isset($params['patient']) && $params['patient'] != "") $patient= $params['patient'];
60     
61     $sortby = "";
62     if (isset($params['sortby']) && $params['sortby'] != "") $sortby = $params['sortby'];
63     
64     $levent = "";
65     if (isset($params['levent']) && $params['levent'] != "") $levent = $params['levent'];
66     
67      $tevent = "";
68     if (isset($params['tevent']) && $params['tevent'] != "") $tevent = $params['tevent'];
69     
70      $event = "";
71     if (isset($params['event']) && $params['event'] != "") $event = $params['event'];
72     if ($event!=""){
73     if ($sortby == "comments") $sortby = "description";
74     if ($sortby == "groupname") $sortby = ""; //VicarePlus :: since there is no groupname in extended_log
75     if ($sortby == "success") $sortby = "";   //VicarePlus :: since there is no success field in extended_log
76     if ($sortby == "checksum") $sortby = "";  //VicarePlus :: since there is no checksum field in extended_log
77     $columns = "DISTINCT date, event, user, recipient,patient_id,description";
78     $sql = "SELECT $columns FROM extended_log WHERE date >= '$date1 00:00:00' AND date <= '$date2 23:59:59'";
79     if ($user != "") $sql .= " AND user LIKE '$user'";
80     if ($patient != "") $sql .= " AND patient_id LIKE '$patient'";
81     if ($levent != "") $sql .= " AND event LIKE '$levent%'";
82     if ($sortby != "") $sql .= " ORDER BY ".$sortby." DESC "; // descending order
83     $sql .= " LIMIT 5000";
84     }
85     else
86     {
87     // do the query
88     $sql = "SELECT $cols FROM log WHERE date >= '$date1 00:00:00' AND date <= '$date2 23:59:59'";
89     if ($user != "") $sql .= " AND user LIKE '$user'";
90     if ($patient != "") $sql .= " AND patient_id LIKE '$patient'";
91     if ($levent != "") $sql .= " AND event LIKE '$levent%'";
92     if ($tevent != "") $sql .= " AND event LIKE '%$tevent'";
93     if ($sortby != "") $sql .= " ORDER BY ".$sortby." DESC "; // descending order
94     $sql .= " LIMIT 5000";
95     }
96     $res = sqlStatement($sql);
97     for($iter=0; $row=sqlFetchArray($res); $iter++) {
98         $all[$iter] = $row;
99     }
100     return $all;
103 /* Given an SQL insert/update that was just performeds:
104  * - Find the table and primary id of the row that was created/modified
105  * - Calculate the MD5 checksum of that row (with all the
106  *   column values concatenated together).
107  * - Return the MD5 checksum as a 32 char hex string.
108  * If this is not an insert/update query, return "".
109  * If multiple rows were modified, return "".
110  * If we're unable to determine the row modified, return "".
111  */
112 function sql_checksum_of_modified_row($statement)
114     $table = "";
115     $rid = "";
117     $tokens = preg_split("/[\s,(\'\"]+/", $statement);
118     /* Identifying the id for insert/replace statements for calculating the checksum */
119         if((strcasecmp($tokens[0],"INSERT")==0) || (strcasecmp($tokens[0],"REPLACE")==0)){
120         $table = $tokens[2];
121         $rid = mysql_insert_id($GLOBALS['dbh']);
122         /* For handling the table that doesn't have auto-increment column */
123         if ($rid === 0 || $rid === FALSE) {
124           if($table == "gacl_aco_map" || $table == "gacl_aro_groups_map" || $table == "gacl_aro_map" || $table == "gacl_axo_groups_map" || $table == "gacl_axo_map")
125            $id="acl_id";
126           else if($table == "gacl_groups_aro_map" || $table == "gacl_groups_axo_map")
127           $id="group_id";
128           else
129            $id="id";
130           /* To handle insert statements */
131           if($tokens[3] == $id){
132              for($i=4;$i<count($tokens);$i++){
133                  if(strcasecmp($tokens[$i],"VALUES")==0){
134                   $rid=$tokens[$i+1];
135                      break;
136                 }// if close
137               }//for close
138             }//if close
139         /* To handle replace statements */
140           else if(strcasecmp($tokens[3],"SET")==0){
141                  if((strcasecmp($tokens[4],"ID")==0) || (strcasecmp($tokens[4],"`ID`")==0)){
142                   $rid=$tokens[6];
143            }// if close
144         }
146         else {          
147             return "";
148           }
149         }
150     }
151      /* Identifying the id for update statements for calculating the checksum */
152        else if(strcasecmp($tokens[0],"UPDATE")==0){
153         $table = $tokens[1];
155         $offset = 3;
156         $total = count($tokens);
158         /* Identifying the primary key column for the updated record */ 
159         if ($table == "form_physical_exam") {
160             $id = "forms_id";
161         }
162         else if ($table == "claims"){
163             $id = "patient_id";
164         }
165         else if ($table == "openemr_postcalendar_events") {
166             $id = "pc_eid";
167         }
168          else if ($table == "lang_languages"){
169             $id = "lang_id";
170          }
171          else if ($table == "openemr_postcalendar_categories" || $table == "openemr_postcalendar_topics"){
172             $id = "pc_catid";
173          }
174          else if ($table == "openemr_postcalendar_limits"){
175             $id = "pc_limitid";
176          }
177          else if($table == "gacl_aco_map" || $table == "gacl_aro_groups_map" || $table == "gacl_aro_map" || $table == "gacl_axo_groups_map" || $table == "gacl_axo_map"){
178            $id="acl_id";
179           }
180           else if($table == "gacl_groups_aro_map" || $table == "gacl_groups_axo_map"){
181           $id="group_id";
182           }
183            else {
184             $id = "id";
185            }
186         
187          /* Identifying the primary key value for the updated record */
188         while ($offset < $total) {
189             /* There are 4 possible ways that the id=123 can be parsed:
190              * ('id', '=', '123')
191              * ('id=', '123')
192              * ('id=123')
193              * ('id', '=123')
194              */
195             $rid = "";
196            /*id=', '123'*/
197             if (($tokens[$offset] == "$id=") && ($offset + 1 < $total)) {
198                 $rid = $tokens[$offset+1];
199                 break;
200             }
201            /* 'id', '=', '123' */
202             else if ($tokens[$offset] == "$id" && $tokens[$offset+1] == "=" && ($offset+2 < $total)) {
203                 $rid = $tokens[$offset+2];
204                 break;
205              }
206             /*id=123*/
207             else if (strpos($tokens[$offset], "$id=") === 0) {
208                 $tid = substr($tokens[$offset], strlen($id)+1);
209                 if(is_numeric($tid))
210                  $rid=$tid;
211                  break;
212              }
213            /*'id', '=123' */
214              else if($tokens[$offset] == "$id") {
215                 $tid = substr($tokens[$offset+1],1);
216                 if(is_numeric($tid))
217                  $rid=$tid;
218                 break;
219               } 
220             $offset += 1;
221         }//while ($offset < $total)
222     }// else if ($tokens[0] == 'update' || $tokens[0] == 'UPDATE' )
224     if ($table == "" || $rid == "") {
225         return "";
226     }
227    /* Framing sql statements for calculating checksum */ 
228    if ($table == "form_physical_exam") {
229         $sql = "select * from $table where forms_id = $rid";
230     }
231    else if ($table == "claims"){
232                 $sql = "select * from $table where patient_id = $rid";
233         }
234    else if ($table == "openemr_postcalendar_events") {
235             $sql = "select * from $table where pc_eid = $rid";
236         }
237     else if ($table == "lang_languages") {
238             $sql = "select * from $table where lang_id = $rid";
239     }
240     else if ($table == "openemr_postcalendar_categories" || $table == "openemr_postcalendar_topics"){
241             $sql = "select * from $table where pc_catid = $rid";
242          }
243     else if ($table == "openemr_postcalendar_limits"){
244            $sql = "select * from $table where pc_limitid = $rid";
245          }
246     else if ($table ==  "gacl_aco_map" || $table == "gacl_aro_groups_map" || $table == "gacl_aro_map" || $table == "gacl_axo_groups_map" || $table == "gacl_axo_map"){
247            $sql = "select * from $table where acl_id = $rid";
248          }
249      else if($table == "gacl_groups_aro_map" || $table == "gacl_groups_axo_map"){
250            $sql = "select * from $table where group_id = $rid";
251       }
252      else {
253         $sql = "select * from $table where id = $rid";
254     }
255     $results = sqlQuery($sql,'true');    
256     $column_values = "";
257    /* Concatenating the column values for the row inserted/updated */
258     if (is_array($results)) {
259         foreach ($results as $field_name => $field) {
260             $column_values .= $field;
261         }
262     }
263     return md5($column_values);
266 /* Create an XML audit record corresponding to RFC 3881.
267  * The parameters passed are the column values (from table 'log')
268  * for a single audit record.
269  */
270 function create_rfc3881_msg($user, $group, $event, $patient_id, $outcome, $comments)
273     /* Event action codes indicate whether the event is read/write.
274      * C = create, R = read, U = update, D = delete, E = execute
275      */
276     $eventActionCode = 'E';
277     if (substr($event, -7) == "-create") {
278         $eventActionCode = 'C';
279     }
280     else if (substr($event, -7) == "-insert") {
281         $eventActionCode = 'C';
282     }
283     else if (substr($event, -7) == "-select") {
284         $eventActionCode = 'R';
285     }
286     else if (substr($event, -7) == "-update") {
287         $eventActionCode = 'U';
288     }
289     else if (substr($event, -7) == "-delete") {
290         $eventActionCode = 'D';
291     }
293     $date_obj = new DateTime();
294     $eventDateTime = $date_obj->format(DATE_ATOM);
296     /* For EventOutcomeIndicator, 0 = success and 4 = minor error */
297     $eventOutcome = ($outcome === 1) ? 0 : 4;
299     /* The choice of event codes is up to OpenEMR.
300      * We're using the same event codes as
301      * https://iheprofiles.projects.openhealthtools.org/
302      */
303     $eventIDcodeSystemName = "DCM";
304     $eventIDcode = 0;
305     $eventIDdisplayName = $event;
307     if (strpos($event, 'patient-record') !== FALSE) {
308         $eventIDcode = 110110;
309         $eventIDdisplayName = 'Patient Record';
310     }
311     else if (strpos($event, 'view') !== FALSE) {
312         $eventIDCode = 110110;
313         $eventIDdisplayName = 'Patient Record';
314     }
315     else if (strpos($event, 'login') !== FALSE) {
316         $eventIDcode = 110122;
317         $eventIDdisplayName = 'Login';
318     }
319     else if (strpos($event, 'logout') !== FALSE) {
320         $eventIDcode = 110123;
321         $eventIDdisplayName = 'Logout';
322     }
323     else if (strpos($event, 'scheduling') !== FALSE) {
324         $eventIDcode = 110111;
325         $eventIDdisplayName = 'Patient Care Assignment';
326     }
327     else if (strpos($event, 'security-administration') !== FALSE) {
328         $eventIDcode = 110129;
329         $eventIDdisplayName = 'Security Administration';
330     }
333    
335     /* Variables used in ActiveParticipant section, which identifies
336      * the IP address and application of the source and destination.
337      */
338     $srcUserID = $_SERVER['SERVER_NAME'] . '|OpenEMR';
339     $srcNetwork = $_SERVER['SERVER_ADDR'];
340     $destUserID = $GLOBALS['atna_audit_host'];
341     $destNetwork = $GLOBALS['atna_audit_host'];
343     $userID = $user;
344     $userTypeCode = 1;
345     $userRole = 6;
346     $userCode = 11;
347     $userDisplayName = 'User Identifier';
349     $patientID = "";
350     $patientTypeCode = "";
351     $patientRole = "";
352     $patientCode = "";
353     $patientDisplayName = "";
355     if ($eventIdDisplayName == 'Patient Record') {
356         $patientID = $patient_id;
357         $pattientTypeCode = 1;
358         $patientRole = 1;
359         $patientCode = 2;
360         $patientDisplayName = 'Patient Number';
361     }
363     /* Construct the XML audit message, and save to $msg */
364     $msg =  '<?xml version="1.0" encoding="ASCII"?>';
365     $msg .= '<AuditMessage xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ';
366     $msg .= 'xsi:noNamespaceSchemaLocation="healthcare-security-audit.xsd">';
368     /* Indicate the event code, text name, read/write type, and date/time */
369     $msg .= "<EventIdentification EventActionCode=\"$eventActionCode\" ";
370     $msg .= "EventDateTime=\"$eventDateTime\" ";
371     $msg .= "EventOutcomeIndicator=\"$eventOutcome\">";
372     $msg .= "<EventID code=\"eventIDcode\" displayName=\"$eventIDdisplayName\" ";
373     $msg .= "codeSystemName=\"DCM\" />";
374     $msg .= "</EventIdentification>";
376     /* Indicate the IP address and application of the source and destination */
377     $msg .= "<ActiveParticipant UserID=\"$srcUserID\" UserIsRequestor=\"true\" ";
378     $msg .= "NetworkAccessPointID=\"$srcNetwork\" NetworkAccessPointTypeCode=\"2\" >";
379     $msg .= "<RoleIDCode code=\"110153\" displayName=\"Source\" codeSystemName=\"DCM\" />";
380     $msg .= "</ActiveParticipant>";
381     $msg .= "<ActiveParticipant UserID=\"$destUserID\" UserIsRequestor=\"false\" ";
382     $msg .= "NetworkAccessPointID=\"$destNetwork\" NetworkAccessPointTypeCode=\"2\" >";
383     $msg .= "<RoleIDCode code=\"110152\" displayName=\"Destination\" codeSystemName=\"DCM\" />";
384     $msg .= "</ActiveParticipant>";
386     $msg .= "<AuditSourceIdentification AuditSourceID=\"$srcUserID\" />";
388     /* Indicate the username who generated this audit record */
389     $msg .= "<ParticipantObjectIdentification ParticipantObjectID=\"$user\" ";
390     $msg .= "ParticipantObjectTypeCode=\"1\" ";
391     $msg .= "ParticipantObjectTypeCodeRole=\"6\" >";
392     $msg .= "<ParticipantObjectIDTypeCode code=\"11\" ";
393     $msg .= "displayName=\"User Identifier\" ";
394     $msg .= "codeSystemName=\"RFC-3881\" /></ParticipantObjectIdentification>";
396     if ($eventIDdisplayName == 'Patient Record' && $patient_id != 0) {
397         $msg .= "<ParticipantObjectIdentification ParticipantObjectID=\"$patient_id\" ";
398         $msg .= "ParticipantObjectTypeCode=\"1\" ";
399         $msg .= "ParticipantObjectTypeCodeRole=\"1\" >";
400         $msg .= "<ParticipantObjectIDTypeCode code=\"2\" ";
401         $msg .= "displayName=\"Patient Number\" ";
402         $msg .= "codeSystemName=\"RFC-3881\" /></ParticipantObjectIdentification>";
403     }
404     $msg .= "</AuditMessage>";
406     /* Add the syslog header */
407     $date_obj = new DateTime($date);
408     $datestr= $date_obj->format(DATE_ATOM);
409     $msg = "<13> " . $datestr . " " . $_SERVER['SERVER_NAME'] . " " . $msg;
410     return $msg;
414 /* Create a TLS (SSLv3) connection to the given host/port.
415  * $localcert is the path to a PEM file with a client certificate and private key.
416  * $cafile is the path to the CA certificate file, for
417  *  authenticating the remote machine's certificate.
418  * If $cafile is "", the remote machine's certificate is not verified.
419  * If $localcert is "", we don't pass a client certificate in the connection.
421  * Return a stream resource that can be used with fwrite(), fread(), etc.
422  * Returns FALSE on error.
423  */
424 function create_tls_conn($host, $port, $localcert, $cafile) {
425     $sslopts = array();
426     if ($cafile !== null && $cafile != "") {
427         $sslopts['cafile'] = $cafile;
428         $sslopts['verify_peer'] = TRUE;
429         $sslopts['verify_depth'] = 10;
430     }
431     if ($localcert !== null && $localcert != "") {
432         $sslopts['local_cert'] = $localcert;
433     }
434     $opts = array('tls' => $sslopts, 'ssl' => $sslopts);
435     $ctx = stream_context_create($opts);
436     $timeout = 60;
437     $flags = STREAM_CLIENT_CONNECT;
439     $olderr = error_reporting(0);
440     $conn = stream_socket_client('tls://' . $host . ":" . $port, $errno, $errstr,
441                                  $timeout, $flags, $ctx);
442     error_reporting($olderr);
443     return $conn;
447 /* This function is used to send audit records to an Audit Repository Server,
448  * as described in the Audit Trail and Node Authentication (ATNA) standard.
449  * Given the fields in a single audit record:
450  * - Create an XML audit message according to RFC 3881, including the RFC5425 syslog header.
451  * - Create a TLS connection that performs bi-directions certificate authentication,
452  *   according to RFC 5425.
453  * - Send the XML message on the TLS connection.
454  */
455 function send_atna_audit_msg($user, $group, $event, $patient_id, $outcome, $comments)
457     /* If no ATNA repository server is configured, return */
458     if ($GLOBALS['atna_audit_host'] === null || $GLOBALS['atna_audit_host'] == "" || !($GLOBALS['enable_atna_audit'])) {
459         return;
460     }
461     $host = $GLOBALS['atna_audit_host'];
462     $port = $GLOBALS['atna_audit_port'];
463     $localcert = $GLOBALS['atna_audit_localcert'];
464     $cacert = $GLOBALS['atna_audit_cacert'];
465     $conn = create_tls_conn($host, $port, $localcert, $cacert);
466     if ($conn !== FALSE) {
467         $msg = create_rfc3881_msg($user, $group, $event, $patient_id, $outcome, $comments);
468         $len = strlen($msg);
469         fwrite($conn, $msg);
470         fclose($conn);
471     }
475 /* Add an entry into the audit log table, indicating that an
476  * SQL query was performed. $outcome is true if the statement
477  * successfully completed.  Determine the event type based on
478  * the tables present in the SQL query.
479  */
480 function auditSQLEvent($statement, $outcome)
482     $user =  $_SESSION['authUser'];
483         /* Don't log anything if the audit logging is not enabled. Exception for "emergency" users */
484    if (!($GLOBALS['enable_auditlog']))
485    {
486             if ((soundex($user) != soundex("emergency")) && (soundex($user) != soundex("breakglass")))
487             return;
488    }
489 // ViCarePlus : Fix for Audit Issue :: Sep 24, 2010 
491 // Issue:  When the audit logging is enabled and when SELECT QUERY (query=1 in globals.php) is enabled to log, 
492 // the issue of LAST_INSERT_ID arises.  
493 // This is because, the function sql_checksum_of_modified_row() is triggered more than 
494 // once for SELECT Queries and thus the expected value (LAST_INSERT_ID) in the $GLOBALS['lastidado'] is getting altered. 
495 // Since, the $GLOBALS['lastidado'] is manipulated by the other function calls(sql_checksum_of_modified_row), 
496 // this issue is arised.
498 // Fix:
499 // The task of assigning LAST_INSERT_ID  to a global variable $GLOBALS['lastidado']  is moved from sql.inc to this file.
500 // Following code will get executed, when (a) when audit is enabled (b) When break glass is invoked.
501 // Retrieve LAST_INSERT_ID and assign it to a global variable and eventually it can be used by other functions.
502     $lastid=mysql_insert_id($GLOBALS['dbh']);
503     $GLOBALS['lastidado']=$lastid;
504 // ViCarePlus : Audit fix - ends here :: Sep 24,2010 
506    $statement = trim($statement);
508     /* Don't audit SQL statements done to the audit log,
509      * or we'll have an infinite loop.
510      */
511     if ((stripos($statement, "insert into log") !== FALSE) ||
512         (stripos($statement, "FROM log ") !== FALSE) ) {
513         return;
514     }
516     $group = $_SESSION['authGroup'];
517     $comments = $statement;
518     $success = 1;
519     $checksum = "";
520     if ($outcome === FALSE) {
521         $success = 0;
522     }
523     if ($outcome !== FALSE) {
524         $checksum = sql_checksum_of_modified_row($statement);
525     }
526     /* Determine the query type (select, update, insert, delete) */
527     $querytype = "select";
528     $querytypes = array("select", "update", "insert", "delete","replace");
529     foreach ($querytypes as $qtype) {
530         if (stripos($statement, $qtype) === 0) {
531             $querytype = $qtype;
532         }
533     }
535     /* Determine the audit event based on the database tables */
536     $event = "other";
537     $tables = array("billing" => "patient-record",
538                     "claims" => "patient-record",
539                     "employer_data" => "patient-record",
540                     "forms" => "patient-record",
541                     "form_encounter" => "patient-record",
542                     "form_dictation" => "patient-record",
543                     "form_misc_billing_options" => "patient-record",
544                     "form_reviewofs" => "patient-record",
545                     "form_ros" => "patient-record",
546                     "form_soap" => "patient-record",
547                     "form_vitals" => "patient-record",
548                     "history_data" => "patient-record",
549                     "immunizations" => "patient-record",
550                     "insurance_data" => "patient-record",
551                     "issue_encounter" => "patient-record",
552                     "lists" => "patient-record",
553                     "patient_data" => "patient-record",
554                     "payments" => "patient-record",
555                     "pnotes" => "patient-record",
556                     "onotes" => "patient-record",
557                     "prescriptions" => "order",
558                     "transactions" => "patient-record",
559                     "facility" => "security-administration",
560                     "pharmacies" => "security-administration",
561                     "addresses" => "security-administration",
562                     "phone_numbers" => "security-administration",
563                     "x12_partners" => "security-administration",
564                     "insurance_companies" => "security-administration",
565                     "codes" => "security-administration",
566                     "registry" => "security-administration", 
567                     "users" => "security-administration",
568                     "groups" => "security-administration",
569                     "openemr_postcalendar_events" => "scheduling",
570                                 "openemr_postcalendar_categories" => "security-administration",
571                                 "openemr_postcalendar_limits" => "security-administration",
572                                 "openemr_postcalendar_topics" => "security-administration",
573                                 "gacl_acl" => "security-administration",
574                                 "gacl_acl_sections" => "security-administration",
575                                 "gacl_acl_seq" => "security-administration",
576                                 "gacl_aco" => "security-administration",
577                                 "gacl_aco_map" => "security-administration",
578                                 "gacl_aco_sections" => "security-administration",
579                                 "gacl_aco_sections_seq" => "security-administration",
580                                 "gacl_aco_seq" => "security-administration",
581                                 "gacl_aro" => "security-administration",
582                                 "gacl_aro_groups" => "security-administration",                                 
583                                 "gacl_aro_groups_id_seq" => "security-administration",
584                                 "gacl_aro_groups_map" => "security-administration",
585                                 "gacl_aro_map" => "security-administration",
586                                 "gacl_aro_sections" => "security-administration",
587                                 "gacl_aro_sections_seq" => "security-administration",
588                                 "gacl_aro_seq" => "security-administration",
589                                 "gacl_axo" => "security-administration",
590                                 "gacl_axo_groups" => "security-administration",
591                                 "gacl_axo_groups_map" => "security-administration",
592                                 "gacl_axo_map" => "security-administration",
593                                 "gacl_axo_sections" => "security-administration",
594                                 "gacl_groups_aro_map" => "security-administration",
595                                 "gacl_groups_axo_map" => "security-administration",
596                                 "gacl_phpgacl" => "security-administration"                             
597                   );
599     /* When searching for table names, truncate the SQL statement,
600      * removing any WHERE, SET, or VALUE clauses.
601      */
602         $truncated_sql = $statement;
603         $truncated_sql = str_replace("\n", " ", $truncated_sql);
604         if ($querytype == "select") {
605         $startwhere = stripos($truncated_sql, " where ");
606         if ($startwhere > 0) {
607         $truncated_sql = substr($truncated_sql, 0, $startwhere);
608     }
610         else {
611      $startparen = stripos($truncated_sql, "(" );
612      $startset = stripos($truncated_sql, " set ");
613      $startvalues = stripos($truncated_sql, " values ");
615         if ($startparen > 0) {
616             $truncated_sql = substr($truncated_sql, 0, $startparen);
617         }
618         if ($startvalues > 0) {
619             $truncated_sql = substr($truncated_sql, 0, $startvalues);
620         }
621         if ($startset > 0) {
622             $truncated_sql = substr($truncated_sql, 0, $startset);
623         }
624     }
625     foreach ($tables as $table => $value) {
626         if (strpos($truncated_sql, $table) !== FALSE) {
627             $event = $value;
628              break;
629         }
630       else if (strpos($truncated_sql, "form_") !== FALSE) {
631             $event = "patient-record";
632              break;
633         }
634     }
636     /* Avoid filling the audit log with trivial SELECT statements.
637      * Skip SELECTs from unknown tables.  
638      * Skip SELECT count() statements.
639      * Skip the SELECT made by the authCheckSession() function.
640      */
641     if ($querytype == "select") {
642         if ($event == "other")
643             return;
644         if (stripos($statement, "SELECT count(" ) === 0)
645             return;
646         if (stripos($statement, "select username, password from users") === 0)
647             return;
648     }
651     /* If the event is a patient-record, then note the patient id */
652     $pid = 0;
653     if ($event == "patient-record") {
654         if (array_key_exists('pid', $_SESSION) && $_SESSION['pid'] != '') {
655             $pid = $_SESSION['pid'];
656         }
657     }
659     /* If query events are not enabled, don't log them */
660     if (($querytype == "select") && !($GLOBALS['audit_events_query']))
661     { 
662        if ((soundex($user) != soundex("emergency")) && (soundex($user) != soundex("breakglass")))
663        return;
664     }
666     if (!($GLOBALS["audit_events_${event}"])) 
667     {
668         if ((soundex($user) != soundex("emergency")) && (soundex($user) != soundex("breakglass")))
669         return;
670     }
671            
673     $event = $event . "-" . $querytype;
675     $adodb = $GLOBALS['adodb']['db'];
676    
677     // ViSolve : Don't log sequences - to avoid the affect due to GenID calls
678     if (strpos($comments, "sequences") !== FALSE) return;
680     $sql = "insert into log (date, event, user, groupname, comments, patient_id, success, checksum,crt_user) " .
681          "values ( NOW(), " . 
682          $adodb->qstr($event) . ", " .
683          $adodb->qstr($user) . "," . 
684          $adodb->qstr($group) . "," .
685          $adodb->qstr($comments) . "," .
686          $adodb->qstr($pid) . "," .
687          $adodb->qstr($success) . "," . 
688          $adodb->qstr($checksum) . "," .
689          $adodb->qstr($_SERVER['SSL_CLIENT_S_DN_CN']) .")";
691     //$ret = sqlInsertClean($sql);
692     //ViSolve: Call the new function created for audit logs
693     sqlInsertClean_audit($sql);
694     send_atna_audit_msg($user, $group, $event, $pid, $success, $comments);
695     //return $ret;
698  * Record the patient disclosures.
699  * @param $dates    - The date when the disclosures are sent to the thrid party.
700  * @param $event    - The type of the disclosure.
701  * @param $pid      - The id of the patient for whom the disclosures are recorded.
702  * @param $comment  - The recipient name and description of the disclosure.
703  * @uname           - The username who is recording the disclosure.
704  */
705 function recordDisclosure($dates,$event,$pid,$recipient,$description,$user)
707         $adodb = $GLOBALS['adodb']['db'];
708         $crt_user= $_SERVER['SSL_CLIENT_S_DN_CN'];
709         $groupname=$_SESSION['authProvider'];
710         $success=1;
711         $sql = "insert into extended_log ( date, event, user, recipient, patient_id, description) " .
712             "values (" . $adodb->qstr($dates) . "," . $adodb->qstr($event) . "," . $adodb->qstr($user) .
713             "," . $adodb->qstr($recipient) . ",".
714             $adodb->qstr($pid) ."," .
715             $adodb->qstr($description) .")";
716         $ret = sqlInsertClean_audit($sql);
719  * Edit the disclosures that is recorded.
720  * @param $dates  - The date when the disclosures are sent to the thrid party.
721  * @param $event  - The type of the disclosure.
722  * param $comment - The recipient and the description of the disclosure are appended.
723  * $logeventid    - The id of the record which is to be edited.
724  */
725 function updateRecordedDisclosure($dates,$event,$recipient,$description,$disclosure_id)
727          $adodb = $GLOBALS['adodb']['db'];
728          $sql="update extended_log set
729                 event=" . $adodb->qstr($event) . ",
730                 date=" .  $adodb->qstr($dates) . ",
731                 recipient=" . $adodb->qstr($recipient) . ",
732                 description=" . $adodb->qstr($description) . "
733                 where id=" . $adodb->qstr($disclosure_id) . "";
734           $ret = sqlInsertClean_audit($sql);
737  * Delete the disclosures that is recorded.
738  * $deleteid - The id of the record which is to be deleted.
739  */
740 function deleteDisclosure($deletelid)
742         $sql="delete from extended_log where id='$deletelid'";
743         $ret = sqlInsertClean_audit($sql);