Merge pull request #1455 from bradymiller/openssl-stuff_1
[openemr.git] / library / log.inc
blobdcea2fdd30ac64e16894b538c2edcb6c21e5ae7e
1 <?php
3 function newEvent($event, $user, $groupname, $success, $comments = "", $patient_id = null, $log_from = 'open-emr', $menu_item = 'dashboard', $ccda_doc_id = 0)
5     $adodb = $GLOBALS['adodb']['db'];
6     $crt_user=isset($_SERVER['SSL_CLIENT_S_DN_CN']) ?  $_SERVER['SSL_CLIENT_S_DN_CN'] : null;
8     $category = $event;
9     // Special case delete for lists table
10     if ($event == 'delete') {
11         $category = eventCategoryFinder($comments, $event, '');
12     }
14     // deal with comments encryption, if turned on
15     $encrypt_comment = 'No';
16     if (!empty($comments)) {
17         if ($GLOBALS["enable_auditlog_encryption"]) {
18             $comments =  aes256Encrypt($comments);
19             $encrypt_comment = 'Yes';
20         }
21     }
23     if ($log_from == 'patient-portal') {
24         $sqlMenuItems = "SELECT * FROM patient_portal_menu";
26         $resMenuItems = sqlStatement($sqlMenuItems);
27         for ($iter=0; $rowMenuItem=sqlFetchArray($resMenuItems); $iter++) {
28             $menuItems[$rowMenuItem['patient_portal_menu_id']] = $rowMenuItem['menu_name'];
29         }
31         $menuItemId = array_search($menu_item, $menuItems);
32         $sql = "insert into log ( date, event,category, user, patient_id, groupname, success, comments,
33                 log_from, menu_item_id, crt_user, ccda_doc_id) values ( NOW(), ?,'Patient Portal', ?, ?, ?, ?, ?, ?, ?,?, ?)";
34         $ret = sqlStatementNoLog($sql, array($event, $user, $patient_id, $groupname, $success, $comments,$log_from, $menuItemId,$crt_user, $ccda_doc_id));
35     } else {
36     /* More details added to the log */
37         $sql = "insert into log ( date, event,category, user, groupname, success, comments, crt_user, patient_id) " .
38             "values ( NOW(), " . $adodb->qstr($event) . ",". $adodb->qstr($category) . "," . $adodb->qstr($user) .
39             "," . $adodb->qstr($groupname) . "," . $adodb->qstr($success) . "," .
40             $adodb->qstr($comments) ."," .
41             $adodb->qstr($crt_user) ."," . $adodb->qstr($patient_id). ")";
43         $ret = sqlInsertClean_audit($sql);
44     }
46     // Send item to log_comment_encrypt for comment encyption tracking
47     $last_log_id = $GLOBALS['adodb']['db']->Insert_ID();
48     $encryptLogQry = "INSERT INTO log_comment_encrypt (log_id, encrypt, checksum, `version`) ".
49                      " VALUES ( ".
50                      $adodb->qstr($last_log_id) . "," .
51                      $adodb->qstr($encrypt_comment) . "," .
52                      "'', '1')";
53     sqlInsertClean_audit($encryptLogQry);
55     if (($patient_id=="NULL") || ($patient_id==null)) {
56         $patient_id=0;
57     }
59     send_atna_audit_msg($user, $groupname, $event, $patient_id, $success, $comments);
62 function getEventByDate($date, $user = "", $cols = "DISTINCT date, event, user, groupname, patient_id, success, comments, checksum")
64     $sql = "SELECT $cols FROM log WHERE date >= '$date 00:00:00' AND date <= '$date 23:59:59'";
65     if ($user) {
66         $sql .= " AND user LIKE '$user'";
67     }
69     $sql .= " ORDER BY date DESC LIMIT 5000";
70     $res = sqlStatement($sql);
71     for ($iter=0; $row=sqlFetchArray($res); $iter++) {
72         $all[$iter] = $row;
73     }
75     return $all;
78 /******************
79  * Get records from the LOG and Extended_Log table
80  * using the optional parameters:
81  *   date : a specific date  (defaults to today)
82  *   user : a specific user  (defaults to none)
83  *   cols : gather specific columns  (defaults to date,event,user,groupname,comments)
84  *   sortby : sort the results by  (defaults to none)
85  * RETURNS:
86  *   array of results
87  ******************/
88 function getEvents($params)
90     // parse the parameters
91     $cols = "DISTINCT date, event, category, user, groupname, patient_id, success, comments,checksum,crt_user, id ";
92     if (isset($params['cols']) && $params['cols'] != "") {
93         $cols = $params['cols'];
94     }
96     $date1 = date("Y-m-d H:i:s", time());
97     if (isset($params['sdate']) && $params['sdate'] != "") {
98         $date1= $params['sdate'];
99     }
101     $date2 = date("Y-m-d H:i:s", time());
102     if (isset($params['edate']) && $params['edate'] != "") {
103         $date2= $params['edate'];
104     }
106     $user = "";
107     if (isset($params['user']) && $params['user'] != "") {
108         $user= $params['user'];
109     }
111     //VicarePlus :: For Generating log with patient id.
112     $patient = "";
113     if (isset($params['patient']) && $params['patient'] != "") {
114         $patient= $params['patient'];
115     }
117     $sortby = "";
118     if (isset($params['sortby']) && $params['sortby'] != "") {
119         $sortby = $params['sortby'];
120     }
122     $levent = "";
123     if (isset($params['levent']) && $params['levent'] != "") {
124         $levent = $params['levent'];
125     }
127      $tevent = "";
128     if (isset($params['tevent']) && $params['tevent'] != "") {
129         $tevent = $params['tevent'];
130     }
132     $direction = 'asc';
133     if (isset($params['direction']) && $params['direction'] != "") {
134         $direction = $params['direction'];
135     }
137      $event = "";
138     if (isset($params['event']) && $params['event'] != "") {
139         $event = $params['event'];
140     }
142     if ($event!="") {
143         if ($sortby == "comments") {
144             $sortby = "description";
145         }
147         if ($sortby == "groupname") {
148             $sortby = ""; //VicarePlus :: since there is no groupname in extended_log
149         }
151         if ($sortby == "success") {
152             $sortby = "";   //VicarePlus :: since there is no success field in extended_log
153         }
155         if ($sortby == "checksum") {
156             $sortby = "";  //VicarePlus :: since there is no checksum field in extended_log
157         }
159         if ($sortby == "category") {
160             $sortby = "";  //VicarePlus :: since there is no category field in extended_log
161         }
163         $sqlBindArray = array();
164         $columns = "DISTINCT date, event, user, recipient,patient_id,description";
165         $sql = "SELECT $columns FROM extended_log WHERE date >= ? AND date <= ?";
166         array_push($sqlBindArray, $date1, $date2);
168         if ($user != "") {
169             $sql .= " AND user LIKE ?";
170             array_push($sqlBindArray, $user);
171         }
173         if ($patient != "") {
174             $sql .= " AND patient_id LIKE ?";
175             array_push($sqlBindArray, $patient);
176         }
178         if ($levent != "") {
179             $sql .= " AND event LIKE ?";
180             array_push($sqlBindArray, $levent . "%");
181         }
183         if ($sortby != "") {
184             $sql .= " ORDER BY " . escape_sql_column_name($sortby, array('extended_log')) . " DESC"; // descending order
185         }
187         $sql .= " LIMIT 5000";
188     } else {
189     // do the query
190         $sqlBindArray = array();
191         $sql = "SELECT $cols FROM log WHERE date >= ? AND date <= ?";
192         array_push($sqlBindArray, $date1, $date2);
194         if ($user != "") {
195             $sql .= " AND user LIKE ?";
196             array_push($sqlBindArray, $user);
197         }
199         if ($patient != "") {
200             $sql .= " AND patient_id LIKE ?";
201             array_push($sqlBindArray, $patient);
202         }
204         if ($levent != "") {
205             $sql .= " AND event LIKE ?";
206             array_push($sqlBindArray, $levent . "%");
207         }
209         if ($tevent != "") {
210             $sql .= " AND event LIKE ?";
211             array_push($sqlBindArray, "%" . $tevent);
212         }
214         if ($sortby != "") {
215             $sql .= " ORDER BY ".$sortby."  ".escape_sort_order($direction); // descending order
216         }
218         $sql .= " LIMIT 5000";
219     }
221     $res = sqlStatement($sql, $sqlBindArray);
222     for ($iter=0; $row=sqlFetchArray($res); $iter++) {
223         $all[$iter] = $row;
224     }
226     return $all;
229 /* Given an SQL insert/update that was just performeds:
230  * - Find the table and primary id of the row that was created/modified
231  * - Calculate the SHA1 checksum of that row (with all the
232  *   column values concatenated together).
233  * - Return the SHA1 checksum as a 40 char hex string.
234  * If this is not an insert/update query, return "".
235  * If multiple rows were modified, return "".
236  * If we're unable to determine the row modified, return "".
238  * TODO: May need to incorporate the binded stuff (still analyzing)
240  */
241 function sql_checksum_of_modified_row($statement)
243     $table = "";
244     $rid = "";
246     $tokens = preg_split("/[\s,(\'\"]+/", $statement);
247     /* Identifying the id for insert/replace statements for calculating the checksum */
248     if ((strcasecmp($tokens[0], "INSERT")==0) || (strcasecmp($tokens[0], "REPLACE")==0)) {
249         $table = $tokens[2];
250         $rid = generic_sql_insert_id();
251     /* For handling the table that doesn't have auto-increment column */
252         if ($rid === 0 || $rid === false) {
253             if ($table == "gacl_aco_map" || $table == "gacl_aro_groups_map" || $table == "gacl_aro_map" || $table == "gacl_axo_groups_map" || $table == "gacl_axo_map") {
254                 $id="acl_id";
255             } else if ($table == "gacl_groups_aro_map" || $table == "gacl_groups_axo_map") {
256                 $id="group_id";
257             } else {
258                 $id="id";
259             }
261       /* To handle insert statements */
262             if ($tokens[3] == $id) {
263                 for ($i=4; $i<count($tokens); $i++) {
264                     if (strcasecmp($tokens[$i], "VALUES")==0) {
265                              $rid=$tokens[$i+1];
266                                 break;
267                     }// if close
268                 }//for close
269             } //if close
270     /* To handle replace statements */
271             else if (strcasecmp($tokens[3], "SET")==0) {
272                 if ((strcasecmp($tokens[4], "ID")==0) || (strcasecmp($tokens[4], "`ID`")==0)) {
273                          $rid=$tokens[6];
274                 }// if close
275             } else {
276                     return "";
277             }
278         }
279     } /* Identifying the id for update statements for calculating the checksum */
280     else if (strcasecmp($tokens[0], "UPDATE")==0) {
281         $table = $tokens[1];
283         $offset = 3;
284         $total = count($tokens);
286         /* Identifying the primary key column for the updated record */
287         if ($table == "form_physical_exam") {
288             $id = "forms_id";
289         } else if ($table == "claims") {
290             $id = "patient_id";
291         } else if ($table == "openemr_postcalendar_events") {
292             $id = "pc_eid";
293         } else if ($table == "lang_languages") {
294             $id = "lang_id";
295         } else if ($table == "openemr_postcalendar_categories" || $table == "openemr_postcalendar_topics") {
296             $id = "pc_catid";
297         } else if ($table == "openemr_postcalendar_limits") {
298             $id = "pc_limitid";
299         } else if ($table == "gacl_aco_map" || $table == "gacl_aro_groups_map" || $table == "gacl_aro_map" || $table == "gacl_axo_groups_map" || $table == "gacl_axo_map") {
300             $id="acl_id";
301         } else if ($table == "gacl_groups_aro_map" || $table == "gacl_groups_axo_map") {
302             $id="group_id";
303         } else {
304             $id = "id";
305         }
307       /* Identifying the primary key value for the updated record */
308         while ($offset < $total) {
309             /* There are 4 possible ways that the id=123 can be parsed:
310             * ('id', '=', '123')
311             * ('id=', '123')
312             * ('id=123')
313             * ('id', '=123')
314             */
315             $rid = "";
316             /*id=', '123'*/
317             if (($tokens[$offset] == "$id=") && ($offset + 1 < $total)) {
318                 $rid = $tokens[$offset+1];
319                 break;
320             } /* 'id', '=', '123' */
321             else if ($tokens[$offset] == "$id" && $tokens[$offset+1] == "=" && ($offset+2 < $total)) {
322                 $rid = $tokens[$offset+2];
323                 break;
324             } /*id=123*/
325             else if (strpos($tokens[$offset], "$id=") === 0) {
326                     $tid = substr($tokens[$offset], strlen($id)+1);
327                 if (is_numeric($tid)) {
328                     $rid=$tid;
329                 }
331                  break;
332             } /*'id', '=123' */
333             else if ($tokens[$offset] == "$id") {
334                  $tid = substr($tokens[$offset+1], 1);
335                 if (is_numeric($tid)) {
336                     $rid=$tid;
337                 }
339                  break;
340             }
342              $offset += 1;
343         }//while ($offset < $total)
344     }// else if ($tokens[0] == 'update' || $tokens[0] == 'UPDATE' )
346     if ($table == "" || $rid == "") {
347         return "";
348     }
350    /* Framing sql statements for calculating checksum */
351     if ($table == "form_physical_exam") {
352         $sql = "select * from $table where forms_id = $rid";
353     } else if ($table == "claims") {
354         $sql = "select * from $table where patient_id = $rid";
355     } else if ($table == "openemr_postcalendar_events") {
356         $sql = "select * from $table where pc_eid = $rid";
357     } else if ($table == "lang_languages") {
358         $sql = "select * from $table where lang_id = $rid";
359     } else if ($table == "openemr_postcalendar_categories" || $table == "openemr_postcalendar_topics") {
360         $sql = "select * from $table where pc_catid = $rid";
361     } else if ($table == "openemr_postcalendar_limits") {
362         $sql = "select * from $table where pc_limitid = $rid";
363     } else if ($table ==  "gacl_aco_map" || $table == "gacl_aro_groups_map" || $table == "gacl_aro_map" || $table == "gacl_axo_groups_map" || $table == "gacl_axo_map") {
364         $sql = "select * from $table where acl_id = $rid";
365     } else if ($table == "gacl_groups_aro_map" || $table == "gacl_groups_axo_map") {
366         $sql = "select * from $table where group_id = $rid";
367     } else {
368         $sql = "select * from $table where id = $rid";
369     }
371     // When this function is working perfectly, can then shift to the
372     // sqlQueryNoLog() function.
373         $results = sqlQueryNoLogIgnoreError($sql);
374         $column_values = "";
375    /* Concatenating the column values for the row inserted/updated */
376     if (is_array($results)) {
377         foreach ($results as $field_name => $field) {
378             $column_values .= $field;
379         }
380     }
382     // ViCarePlus: As per NIST standard, the encryption algorithm SHA1 is used
384     //error_log("COLUMN_VALUES: ".$column_values,0);
385         return sha1($column_values);
388 /* Create an XML audit record corresponding to RFC 3881.
389  * The parameters passed are the column values (from table 'log')
390  * for a single audit record.
391  */
392 function create_rfc3881_msg($user, $group, $event, $patient_id, $outcome, $comments)
395     /* Event action codes indicate whether the event is read/write.
396      * C = create, R = read, U = update, D = delete, E = execute
397      */
398     $eventActionCode = 'E';
399     if (substr($event, -7) == "-create") {
400         $eventActionCode = 'C';
401     } else if (substr($event, -7) == "-insert") {
402         $eventActionCode = 'C';
403     } else if (substr($event, -7) == "-select") {
404         $eventActionCode = 'R';
405     } else if (substr($event, -7) == "-update") {
406         $eventActionCode = 'U';
407     } else if (substr($event, -7) == "-delete") {
408         $eventActionCode = 'D';
409     }
411     $date_obj = new DateTime();
412     $eventDateTime = $date_obj->format(DATE_ATOM);
414     /* For EventOutcomeIndicator, 0 = success and 4 = minor error */
415     $eventOutcome = ($outcome === 1) ? 0 : 4;
417     /* The choice of event codes is up to OpenEMR.
418      * We're using the same event codes as
419      * https://iheprofiles.projects.openhealthtools.org/
420      */
421     $eventIDcodeSystemName = "DCM";
422     $eventIDcode = 0;
423     $eventIDdisplayName = $event;
425     if (strpos($event, 'patient-record') !== false) {
426         $eventIDcode = 110110;
427         $eventIDdisplayName = 'Patient Record';
428     } else if (strpos($event, 'view') !== false) {
429         $eventIDCode = 110110;
430         $eventIDdisplayName = 'Patient Record';
431     } else if (strpos($event, 'login') !== false) {
432         $eventIDcode = 110122;
433         $eventIDdisplayName = 'Login';
434     } else if (strpos($event, 'logout') !== false) {
435         $eventIDcode = 110123;
436         $eventIDdisplayName = 'Logout';
437     } else if (strpos($event, 'scheduling') !== false) {
438         $eventIDcode = 110111;
439         $eventIDdisplayName = 'Patient Care Assignment';
440     } else if (strpos($event, 'security-administration') !== false) {
441         $eventIDcode = 110129;
442         $eventIDdisplayName = 'Security Administration';
443     }
448     /* Variables used in ActiveParticipant section, which identifies
449      * the IP address and application of the source and destination.
450      */
451     $srcUserID = $_SERVER['SERVER_NAME'] . '|OpenEMR';
452     $srcNetwork = $_SERVER['SERVER_ADDR'];
453     $destUserID = $GLOBALS['atna_audit_host'];
454     $destNetwork = $GLOBALS['atna_audit_host'];
456     $userID = $user;
457     $userTypeCode = 1;
458     $userRole = 6;
459     $userCode = 11;
460     $userDisplayName = 'User Identifier';
462     $patientID = "";
463     $patientTypeCode = "";
464     $patientRole = "";
465     $patientCode = "";
466     $patientDisplayName = "";
468     if ($eventIDdisplayName == 'Patient Record') {
469         $patientID = $patient_id;
470         $pattientTypeCode = 1;
471         $patientRole = 1;
472         $patientCode = 2;
473         $patientDisplayName = 'Patient Number';
474     }
476     /* Construct the XML audit message, and save to $msg */
477     $msg =  '<?xml version="1.0" encoding="ASCII"?>';
478     $msg .= '<AuditMessage xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ';
479     $msg .= 'xsi:noNamespaceSchemaLocation="healthcare-security-audit.xsd">';
481     /* Indicate the event code, text name, read/write type, and date/time */
482     $msg .= "<EventIdentification EventActionCode=\"$eventActionCode\" ";
483     $msg .= "EventDateTime=\"$eventDateTime\" ";
484     $msg .= "EventOutcomeIndicator=\"$eventOutcome\">";
485     $msg .= "<EventID code=\"eventIDcode\" displayName=\"$eventIDdisplayName\" ";
486     $msg .= "codeSystemName=\"DCM\" />";
487     $msg .= "</EventIdentification>";
489     /* Indicate the IP address and application of the source and destination */
490     $msg .= "<ActiveParticipant UserID=\"$srcUserID\" UserIsRequestor=\"true\" ";
491     $msg .= "NetworkAccessPointID=\"$srcNetwork\" NetworkAccessPointTypeCode=\"2\" >";
492     $msg .= "<RoleIDCode code=\"110153\" displayName=\"Source\" codeSystemName=\"DCM\" />";
493     $msg .= "</ActiveParticipant>";
494     $msg .= "<ActiveParticipant UserID=\"$destUserID\" UserIsRequestor=\"false\" ";
495     $msg .= "NetworkAccessPointID=\"$destNetwork\" NetworkAccessPointTypeCode=\"2\" >";
496     $msg .= "<RoleIDCode code=\"110152\" displayName=\"Destination\" codeSystemName=\"DCM\" />";
497     $msg .= "</ActiveParticipant>";
499     $msg .= "<AuditSourceIdentification AuditSourceID=\"$srcUserID\" />";
501     /* Indicate the username who generated this audit record */
502     $msg .= "<ParticipantObjectIdentification ParticipantObjectID=\"$user\" ";
503     $msg .= "ParticipantObjectTypeCode=\"1\" ";
504     $msg .= "ParticipantObjectTypeCodeRole=\"6\" >";
505     $msg .= "<ParticipantObjectIDTypeCode code=\"11\" ";
506     $msg .= "displayName=\"User Identifier\" ";
507     $msg .= "codeSystemName=\"RFC-3881\" /></ParticipantObjectIdentification>";
509     if ($eventIDdisplayName == 'Patient Record' && $patient_id != 0) {
510         $msg .= "<ParticipantObjectIdentification ParticipantObjectID=\"$patient_id\" ";
511         $msg .= "ParticipantObjectTypeCode=\"1\" ";
512         $msg .= "ParticipantObjectTypeCodeRole=\"1\" >";
513         $msg .= "<ParticipantObjectIDTypeCode code=\"2\" ";
514         $msg .= "displayName=\"Patient Number\" ";
515         $msg .= "codeSystemName=\"RFC-3881\" /></ParticipantObjectIdentification>";
516     }
518     $msg .= "</AuditMessage>";
520     /* Add the syslog header */
521     $date_obj = new DateTime($date);
522     $datestr= $date_obj->format(DATE_ATOM);
523     $msg = "<13> " . $datestr . " " . $_SERVER['SERVER_NAME'] . " " . $msg;
524     return $msg;
528 /* Create a TLS (SSLv3) connection to the given host/port.
529  * $localcert is the path to a PEM file with a client certificate and private key.
530  * $cafile is the path to the CA certificate file, for
531  *  authenticating the remote machine's certificate.
532  * If $cafile is "", the remote machine's certificate is not verified.
533  * If $localcert is "", we don't pass a client certificate in the connection.
535  * Return a stream resource that can be used with fwrite(), fread(), etc.
536  * Returns FALSE on error.
537  */
538 function create_tls_conn($host, $port, $localcert, $cafile)
540     $sslopts = array();
541     if ($cafile !== null && $cafile != "") {
542         $sslopts['cafile'] = $cafile;
543         $sslopts['verify_peer'] = true;
544         $sslopts['verify_depth'] = 10;
545     }
547     if ($localcert !== null && $localcert != "") {
548         $sslopts['local_cert'] = $localcert;
549     }
551     $opts = array('tls' => $sslopts, 'ssl' => $sslopts);
552     $ctx = stream_context_create($opts);
553     $timeout = 60;
554     $flags = STREAM_CLIENT_CONNECT;
556     $olderr = error_reporting(0);
557     $conn = stream_socket_client(
558         'tls://' . $host . ":" . $port,
559         $errno,
560         $errstr,
561         $timeout,
562         $flags,
563         $ctx
564     );
565     error_reporting($olderr);
566     return $conn;
570 /* This function is used to send audit records to an Audit Repository Server,
571  * as described in the Audit Trail and Node Authentication (ATNA) standard.
572  * Given the fields in a single audit record:
573  * - Create an XML audit message according to RFC 3881, including the RFC5425 syslog header.
574  * - Create a TLS connection that performs bi-directions certificate authentication,
575  *   according to RFC 5425.
576  * - Send the XML message on the TLS connection.
577  */
578 function send_atna_audit_msg($user, $group, $event, $patient_id, $outcome, $comments)
580     /* If no ATNA repository server is configured, return */
581     if (empty($GLOBALS['atna_audit_host']) || empty($GLOBALS['enable_atna_audit'])) {
582         return;
583     }
585     $host = $GLOBALS['atna_audit_host'];
586     $port = $GLOBALS['atna_audit_port'];
587     $localcert = $GLOBALS['atna_audit_localcert'];
588     $cacert = $GLOBALS['atna_audit_cacert'];
589     $conn = create_tls_conn($host, $port, $localcert, $cacert);
590     if ($conn !== false) {
591         $msg = create_rfc3881_msg($user, $group, $event, $patient_id, $outcome, $comments);
592         $len = strlen($msg);
593         fwrite($conn, $msg);
594         fclose($conn);
595     }
599 /* Add an entry into the audit log table, indicating that an
600  * SQL query was performed. $outcome is true if the statement
601  * successfully completed.  Determine the event type based on
602  * the tables present in the SQL query.
603  */
604 function auditSQLEvent($statement, $outcome, $binds = null)
606     $user =  isset($_SESSION['authUser']) ? $_SESSION['authUser'] : "";
607     /* Don't log anything if the audit logging is not enabled. Exception for "emergency" users */
608     if (!isset($GLOBALS['enable_auditlog']) || !($GLOBALS['enable_auditlog'])) {
609         if ((soundex($user) != soundex("emergency")) && (soundex($user) != soundex("breakglass"))) {
610             return;
611         }
612     }
615     $statement = trim($statement);
617     /* Don't audit SQL statements done to the audit log,
618      * or we'll have an infinite loop.
619      */
620     if ((stripos($statement, "insert into log") !== false) ||
621         (stripos($statement, "FROM log ") !== false) ) {
622         return;
623     }
625     $group = isset($_SESSION['authGroup']) ?  $_SESSION['authGroup'] : "";
626     $comments = $statement;
628     $processed_binds = "";
629     if (is_array($binds)) {
630         // Need to include the binded variable elements in the logging
631         $first_loop=true;
632         foreach ($binds as $value_bind) {
633             if ($first_loop) {
634                 //no comma
635                 $processed_binds .= "'" . add_escape_custom($value_bind) . "'";
636                 $first_loop=false;
637             } else {
638                 //add a comma
639                 $processed_binds .= ",'" . add_escape_custom($value_bind) . "'";
640             }
641         }
643         if (!empty($processed_binds)) {
644             $processed_binds = "(" . $processed_binds . ")";
645             $comments .= " " . $processed_binds;
646         }
647     }
649     $success = 1;
650     $checksum = "";
651     if ($outcome === false) {
652         $success = 0;
653     }
655     if ($outcome !== false) {
656         // Should use the $statement rather than the processed
657         // variables, which includes the binded stuff. If do
658         // indeed need the binded values, then will need
659         // to include this as a separate array.
661         //error_log("STATEMENT: ".$statement,0);
662         //error_log("BINDS: ".$processed_binds,0);
663         $checksum = sql_checksum_of_modified_row($statement);
664         //error_log("CHECKSUM: ".$checksum,0);
665     }
667     /* Determine the query type (select, update, insert, delete) */
668     $querytype = "select";
669     $querytypes = array("select", "update", "insert", "delete","replace");
670     foreach ($querytypes as $qtype) {
671         if (stripos($statement, $qtype) === 0) {
672             $querytype = $qtype;
673         }
674     }
676     /* Determine the audit event based on the database tables */
677     $event = "other";
678     $category = "other";
679     $tables = array("billing" => "patient-record",
680                     "claims" => "patient-record",
681                     "employer_data" => "patient-record",
682                     "forms" => "patient-record",
683                     "form_encounter" => "patient-record",
684                     "form_dictation" => "patient-record",
685                     "form_misc_billing_options" => "patient-record",
686                     "form_reviewofs" => "patient-record",
687                     "form_ros" => "patient-record",
688                     "form_soap" => "patient-record",
689                     "form_vitals" => "patient-record",
690                     "history_data" => "patient-record",
691                     "immunizations" => "patient-record",
692                     "insurance_data" => "patient-record",
693                     "issue_encounter" => "patient-record",
694                     "lists" => "patient-record",
695                     "patient_data" => "patient-record",
696                     "payments" => "patient-record",
697                     "pnotes" => "patient-record",
698                     "onotes" => "patient-record",
699                     "prescriptions" => "order",
700                     "transactions" => "patient-record",
701                     "amendments" => "patient-record",
702                     "amendments_history" => "patient-record",
703                     "facility" => "security-administration",
704                     "pharmacies" => "security-administration",
705                     "addresses" => "security-administration",
706                     "phone_numbers" => "security-administration",
707                     "x12_partners" => "security-administration",
708                     "insurance_companies" => "security-administration",
709                     "codes" => "security-administration",
710                     "registry" => "security-administration",
711                     "users" => "security-administration",
712                     "groups" => "security-administration",
713                     "openemr_postcalendar_events" => "scheduling",
714                     "openemr_postcalendar_categories" => "security-administration",
715                     "openemr_postcalendar_limits" => "security-administration",
716                     "openemr_postcalendar_topics" => "security-administration",
717                     "gacl_acl" => "security-administration",
718                     "gacl_acl_sections" => "security-administration",
719                     "gacl_acl_seq" => "security-administration",
720                     "gacl_aco" => "security-administration",
721                     "gacl_aco_map" => "security-administration",
722                     "gacl_aco_sections" => "security-administration",
723                     "gacl_aco_sections_seq" => "security-administration",
724                     "gacl_aco_seq" => "security-administration",
725                     "gacl_aro" => "security-administration",
726                     "gacl_aro_groups" => "security-administration",
727                     "gacl_aro_groups_id_seq" => "security-administration",
728                     "gacl_aro_groups_map" => "security-administration",
729                     "gacl_aro_map" => "security-administration",
730                     "gacl_aro_sections" => "security-administration",
731                     "gacl_aro_sections_seq" => "security-administration",
732                     "gacl_aro_seq" => "security-administration",
733                     "gacl_axo" => "security-administration",
734                     "gacl_axo_groups" => "security-administration",
735                     "gacl_axo_groups_map" => "security-administration",
736                     "gacl_axo_map" => "security-administration",
737                     "gacl_axo_sections" => "security-administration",
738                     "gacl_groups_aro_map" => "security-administration",
739                     "gacl_groups_axo_map" => "security-administration",
740                     "gacl_phpgacl" => "security-administration",
741                     "procedure_order" => "lab-order",
742                     "procedure_order_code" => "lab-order",
743                     "procedure_report" => "lab-results",
744                     "procedure_result" => "lab-results");
746     /* When searching for table names, truncate the SQL statement,
747      * removing any WHERE, SET, or VALUE clauses.
748      */
749     $truncated_sql = $statement;
750     $truncated_sql = str_replace("\n", " ", $truncated_sql);
751     if ($querytype == "select") {
752         $startwhere = stripos($truncated_sql, " where ");
753         if ($startwhere > 0) {
754             $truncated_sql = substr($truncated_sql, 0, $startwhere);
755         }
756     } else {
757         $startparen = stripos($truncated_sql, "(");
758         $startset = stripos($truncated_sql, " set ");
759         $startvalues = stripos($truncated_sql, " values ");
761         if ($startparen > 0) {
762             $truncated_sql = substr($truncated_sql, 0, $startparen);
763         }
765         if ($startvalues > 0) {
766             $truncated_sql = substr($truncated_sql, 0, $startvalues);
767         }
769         if ($startset > 0) {
770             $truncated_sql = substr($truncated_sql, 0, $startset);
771         }
772     }
774     foreach ($tables as $table => $value) {
775         if (strpos($truncated_sql, $table) !== false) {
776             $event = $value;
777             $category = eventCategoryFinder($comments, $event, $table);
778             break;
779         } else if (strpos($truncated_sql, "form_") !== false) {
780             $event = "patient-record";
781             $category = eventCategoryFinder($comments, $event, $table);
782              break;
783         }
784     }
786     /* Avoid filling the audit log with trivial SELECT statements.
787      * Skip SELECTs from unknown tables.
788      * Skip SELECT count() statements.
789      * Skip the SELECT made by the authCheckSession() function.
790      */
791     if ($querytype == "select") {
792         if ($event == "other") {
793             return;
794         }
796         if (stripos($statement, "SELECT count(") === 0) {
797             return;
798         }
800         if (stripos($statement, "select username, password from users") === 0) {
801             return;
802         }
803     }
806     /* If the event is a patient-record, then note the patient id */
807     $pid = 0;
808     if ($event == "patient-record") {
809         if (array_key_exists('pid', $_SESSION) && $_SESSION['pid'] != '') {
810             $pid = $_SESSION['pid'];
811         }
812     }
814     /* If query events are not enabled, don't log them */
815     if (($querytype == "select") && !(array_key_exists('audit_events_query', $GLOBALS) && $GLOBALS['audit_events_query'])) {
816         if ((soundex($user) != soundex("emergency")) && (soundex($user) != soundex("breakglass"))) {
817             return;
818         }
819     }
821     if (!($GLOBALS["audit_events_${event}"])) {
822         if ((soundex($user) != soundex("emergency")) && (soundex($user) != soundex("breakglass"))) {
823             return;
824         }
825     }
828     $event = $event . "-" . $querytype;
830     $adodb = $GLOBALS['adodb']['db'];
832     // ViSolve : Don't log sequences - to avoid the affect due to GenID calls
833     if (strpos($comments, "sequences") !== false) {
834         return;
835     }
837     $encrypt_comment = 'No';
838     //July 1, 2014: Ensoftek: Check and encrypt audit logging
839     if (array_key_exists('enable_auditlog_encryption', $GLOBALS) && $GLOBALS["enable_auditlog_encryption"]) {
840         $comments =  aes256Encrypt($comments);
841         $encrypt_comment = 'Yes';
842     }
844     $current_datetime = date("Y-m-d H:i:s");
845     $SSL_CLIENT_S_DN_CN=isset($_SERVER['SSL_CLIENT_S_DN_CN']) ? $_SERVER['SSL_CLIENT_S_DN_CN'] : '';
846     $sql = "insert into log (date, event,category, user, groupname, comments, patient_id, success, checksum,crt_user) " .
847          "values ( ".
848          $adodb->qstr($current_datetime). ", ".
849          $adodb->qstr($event) . ", " .
850          $adodb->qstr($category) . ", " .
851          $adodb->qstr($user) . "," .
852          $adodb->qstr($group) . "," .
853          $adodb->qstr($comments) . "," .
854          $adodb->qstr($pid) . "," .
855          $adodb->qstr($success) . "," .
856          $adodb->qstr($checksum) . "," .
857          $adodb->qstr($SSL_CLIENT_S_DN_CN) .")";
858     sqlInsertClean_audit($sql);
860     $last_log_id = $GLOBALS['adodb']['db']->Insert_ID();
861     $checksumGenerate = '';
862     //July 1, 2014: Ensoftek: Record the encryption checksum in a secondary table(log_comment_encrypt)
863     if ($querytype == 'update') {
864         $concatLogColumns = $current_datetime.$event.$user.$group.$comments.$pid.$success.$checksum.$SSL_CLIENT_S_DN_CN;
865         $checksumGenerate = sha1($concatLogColumns);
866     }
868     $encryptLogQry = "INSERT INTO log_comment_encrypt (log_id, encrypt, checksum, `version`) ".
869                      " VALUES ( ".
870                       $adodb->qstr($last_log_id) . "," .
871                       $adodb->qstr($encrypt_comment) . "," .
872                       $adodb->qstr($checksumGenerate) .", '1')";
873     sqlInsertClean_audit($encryptLogQry);
875     send_atna_audit_msg($user, $group, $event, $pid, $success, $comments);
876     //return $ret;
879 // May-29-2014: Ensoftek: For Auditable events and tamper-resistance (MU2)
880 // Insert Audit Logging Status into the LOG table.
881 function auditSQLAuditTamper($enable)
883     $user =  isset($_SESSION['authUser']) ? $_SESSION['authUser'] : "";
884     $group = isset($_SESSION['authGroup']) ?  $_SESSION['authGroup'] : "";
885     $pid = 0;
886     $checksum = "";
887     $success = 1;
888     $event = "security-administration" . "-" . "insert";
891     $adodb = $GLOBALS['adodb']['db'];
893     if ($enable == "1") {
894         $comments = "Audit Logging Enabled.";
895     } else {
896         $comments = "Audit Logging Disabled.";
897     }
899     $SSL_CLIENT_S_DN_CN=isset($_SERVER['SSL_CLIENT_S_DN_CN']) ? $_SERVER['SSL_CLIENT_S_DN_CN'] : '';
900     $sql = "insert into log (date, event, user, groupname, comments, patient_id, success, checksum,crt_user) " .
901          "values ( NOW(), " .
902          $adodb->qstr($event) . ", " .
903          $adodb->qstr($user) . "," .
904          $adodb->qstr($group) . "," .
905          $adodb->qstr($comments) . "," .
906          $adodb->qstr($pid) . "," .
907          $adodb->qstr($success) . "," .
908          $adodb->qstr($checksum) . "," .
909          $adodb->qstr($SSL_CLIENT_S_DN_CN) .")";
911     sqlInsertClean_audit($sql);
912     send_atna_audit_msg($user, $group, $event, $pid, $success, $comments);
916  * Record the patient disclosures.
917  * @param $dates    - The date when the disclosures are sent to the thrid party.
918  * @param $event    - The type of the disclosure.
919  * @param $pid      - The id of the patient for whom the disclosures are recorded.
920  * @param $comment  - The recipient name and description of the disclosure.
921  * @uname           - The username who is recording the disclosure.
922  */
923 function recordDisclosure($dates, $event, $pid, $recipient, $description, $user)
925         $adodb = $GLOBALS['adodb']['db'];
926         $crt_user= $_SERVER['SSL_CLIENT_S_DN_CN'];
927         $groupname=$_SESSION['authProvider'];
928         $success=1;
929         $sql = "insert into extended_log ( date, event, user, recipient, patient_id, description) " .
930             "values (" . $adodb->qstr($dates) . "," . $adodb->qstr($event) . "," . $adodb->qstr($user) .
931             "," . $adodb->qstr($recipient) . ",".
932             $adodb->qstr($pid) ."," .
933             $adodb->qstr($description) .")";
934         $ret = sqlInsertClean_audit($sql);
937  * Edit the disclosures that is recorded.
938  * @param $dates  - The date when the disclosures are sent to the thrid party.
939  * @param $event  - The type of the disclosure.
940  * param $comment - The recipient and the description of the disclosure are appended.
941  * $logeventid    - The id of the record which is to be edited.
942  */
943 function updateRecordedDisclosure($dates, $event, $recipient, $description, $disclosure_id)
945          $adodb = $GLOBALS['adodb']['db'];
946          $sql="update extended_log set
947                 event=" . $adodb->qstr($event) . ",
948                 date=" .  $adodb->qstr($dates) . ",
949                 recipient=" . $adodb->qstr($recipient) . ",
950                 description=" . $adodb->qstr($description) . "
951                 where id=" . $adodb->qstr($disclosure_id) . "";
952           $ret = sqlInsertClean_audit($sql);
955  * Delete the disclosures that is recorded.
956  * $deleteid - The id of the record which is to be deleted.
957  */
958 function deleteDisclosure($deletelid)
960         $sql="delete from extended_log where id='" . add_escape_custom($deletelid) . "'";
961         $ret = sqlInsertClean_audit($sql);
964 //July 1, 2014: Ensoftek: Function to AES256 encrypt a given string
965 function aes256Encrypt($sValue)
967     if (empty($GLOBALS['key_for_encryption'])) {
968         // Collect the key. If it does not exist, then create it
969         $GLOBALS['key_for_encryption'] = aes256PrepKey();
970     }
972     if (!extension_loaded('openssl')) {
973         error_log("OpenEMR Error : Audit Log with encryption is not working because missing openssl extension.");
974     }
976     $sSecretKey = $GLOBALS['key_for_encryption'];
978     $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('AES-256-CBC'));
980     $processedValue = openssl_encrypt(
981         $sValue,
982         'AES-256-CBC',
983         $sSecretKey,
984         OPENSSL_RAW_DATA,
985         $iv
986     );
988     if (rtrim($sValue) != "" && $processedValue == "") {
989         error_log("OpenEMR Error : Audit Log with encryption is not working.");
990     }
992     // prepend the encrypted value with the $iv
993     return base64_encode($iv . $processedValue);
996 //July 1, 2014: Ensoftek: Function to AES256 decrypt a given string
997 function aes256Decrypt($sValue)
999     if (empty($GLOBALS['key_for_encryption'])) {
1000         // Collect the key. If it does not exist, then create it
1001         $GLOBALS['key_for_encryption'] = aes256PrepKey();
1002     }
1004     $sSecretKey = $GLOBALS['key_for_encryption'];
1006     $ivLength = openssl_cipher_iv_length('AES-256-CBC');
1008     $raw = base64_decode($sValue);
1010     $iv = substr($raw, 0, $ivLength);
1011     $encrypted_data = substr($raw, $ivLength);
1013     return openssl_decrypt(
1014         $encrypted_data,
1015         'AES-256-CBC',
1016         $sSecretKey,
1017         OPENSSL_RAW_DATA,
1018         $iv
1019     );
1022 //July 1, 2014: Ensoftek: Function to AES256 decrypt a given string
1023 function aes256Decrypt_mycrypt($sValue)
1025     $sSecretKey = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");
1026     return rtrim(
1027         mcrypt_decrypt(
1028             MCRYPT_RIJNDAEL_256,
1029             $sSecretKey,
1030             base64_decode($sValue),
1031             MCRYPT_MODE_ECB,
1032             mcrypt_create_iv(
1033                 mcrypt_get_iv_size(
1034                     MCRYPT_RIJNDAEL_256,
1035                     MCRYPT_MODE_ECB
1036                 ),
1037                 MCRYPT_RAND
1038             )
1039         ),
1040         "\0"
1041     );
1044 //July 1, 2014: Ensoftek: Utility function to get data from table(log_comment_encrypt)
1045 function logCommentEncryptData($log_id)
1047     $encryptRow = array();
1048     $logRes = sqlStatement("SELECT * FROM log_comment_encrypt WHERE log_id=?", array($log_id));
1049     while ($logRow = sqlFetchArray($logRes)) {
1050         $encryptRow['encrypt'] = $logRow['encrypt'];
1051         $encryptRow['checksum'] = $logRow['checksum'];
1052         $encryptRow['version'] = $logRow['version'];
1053     }
1055     return $encryptRow;
1058 function aes256PrepKey()
1060     // Collect the key. If it does not exist, then create it
1061     if (!file_exists($GLOBALS['OE_SITE_DIR'] . "/documents/logs_and_misc/methods/one")) {
1062         // Create a key file
1063         // Below will produce a 256bit key (32 bytes equals 256 bits)
1064         $newKey = base64_encode(openssl_random_pseudo_bytes(32));
1065         file_put_contents($GLOBALS['OE_SITE_DIR'] . "/documents/logs_and_misc/methods/one", $newKey);
1066     }
1068     // Collect key from file
1069     $key = base64_decode(rtrim(file_get_contents($GLOBALS['OE_SITE_DIR'] . "/documents/logs_and_misc/methods/one")));
1071     if (empty($key)) {
1072         error_log("OpenEMR Error : Audit Log with encryption is not working. Unable to collect key information or key is empty.");
1073     }
1075     // Return the key
1076     return $key;
1080  * Function used to determine category of the event
1082  */
1083 function eventCategoryFinder($sql, $event, $table)
1085     if ($event == 'delete') {
1086         if (strpos($sql, "lists:") === 0) {
1087             $fieldValues    = explode("'", $sql);
1088             if (in_array('medical_problem', $fieldValues) === true) {
1089                 return 'Problem List';
1090             } else if (in_array('medication', $fieldValues) === true) {
1091                 return 'Medication';
1092             } else if (in_array('allergy', $fieldValues) === true) {
1093                 return 'Allergy';
1094             }
1095         }
1096     }
1098     if ($table == 'lists' || $table == 'lists_touch') {
1099         $trimSQL        = stristr($sql, $table);
1100         $fieldValues    = explode("'", $trimSQL);
1101         if (in_array('medical_problem', $fieldValues) === true) {
1102             return 'Problem List';
1103         } else if (in_array('medication', $fieldValues) === true) {
1104             return 'Medication';
1105         } else if (in_array('allergy', $fieldValues) === true) {
1106             return 'Allergy';
1107         }
1108     } else if ($table == 'immunizations') {
1109         return "Immunization";
1110     } else if ($table == 'form_vitals') {
1111         return "Vitals";
1112     } else if ($table == 'history_data') {
1113         return "Social and Family History";
1114     } else if ($table == 'forms' || $table == 'form_encounter' || strpos($table, 'form_') === 0) {
1115         return "Encounter Form";
1116     } else if ($table == 'insurance_data') {
1117         return "Patient Insurance";
1118     } else if ($table == 'patient_data' || $table == 'employer_data') {
1119         return "Patient Demographics";
1120     } else if ($table == 'payments' || $table == "billing" || $table == "claims") {
1121         return "Billing";
1122     } else if ($table == 'pnotes') {
1123         return "Clinical Mail";
1124     } else if ($table == 'prescriptions') {
1125         return "Medication";
1126     } else if ($table == 'transactions') {
1127         $trimSQL        = stristr($sql, "transactions");
1128         $fieldValues    = explode("'", $trimSQL);
1129         if (in_array("LBTref", $fieldValues)) {
1130             return "Referral";
1131         } else {
1132             return $event;
1133         }
1134     } else if ($table == 'amendments' || $table == 'amendments_history') {
1135         return "Amendments";
1136     } else if ($table == 'openemr_postcalendar_events') {
1137         return "Scheduling";
1138     } else if ($table == 'procedure_order' || $table == 'procedure_order_code') {
1139         return "Lab Order";
1140     } else if ($table == 'procedure_report' || $table == 'procedure_result') {
1141         return "Lab Result";
1142     } else if ($event == 'security-administration') {
1143         return "Security";
1144     }
1146     return $event;