PageRenderTime 62ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/library/log.inc

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