Interim autoloaded library/classes via composer classmap, take 4. (#422)
[openemr.git] / interface / modules / zend_modules / module / Carecoordination / src / Carecoordination / Model / EncountermanagerTable.php
blob8cf657443b66f70e23e42860c9ddabb514d1de60
1 <?php
2 /* +-----------------------------------------------------------------------------+
3 * OpenEMR - Open Source Electronic Medical Record
4 * Copyright (C) 2014 Z&H Consultancy Services Private Limited <sam@zhservices.com>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as
8 * published by the Free Software Foundation, either version 3 of the
9 * License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 * @author Vinish K <vinish@zhservices.com>
20 * @author Riju K P <rijukp@zhservices.com>
21 * +------------------------------------------------------------------------------+
24 namespace Carecoordination\Model;
26 use Zend\Db\TableGateway\AbstractTableGateway;
27 use Application\Model\ApplicationTable;
28 use Zend\Db\Adapter\Driver\Pdo\Result;
29 use ZipArchive;
31 use CouchDB;
32 use DOMPDF;
34 class EncountermanagerTable extends AbstractTableGateway
36 public function getEncounters($data,$getCount=null)
38 $query_data = array();
39 $query = "SELECT pd.fname, pd.lname, pd.mname, date(fe.date) as date, fe.pid, fe.encounter,
40 u.fname as doc_fname, u.mname as doc_mname, u.lname as doc_lname, (select count(encounter) from form_encounter where pid=fe.pid) as enc_count,
41 (SELECT DATE(date) FROM form_encounter WHERE pid=fe.pid ORDER BY date DESC LIMIT 1) as last_visit_date,
42 (select count(*) from ccda where pid=fe.pid and transfer=1) as ccda_transfer_count,
43 (select count(*) from ccda where pid=fe.pid and transfer=1 and status=1) as ccda_successfull_transfer_count
44 FROM form_encounter AS fe
45 JOIN patient_data AS pd ON pd.pid=fe.pid
46 LEFT JOIN users AS u ON u.id=fe.provider_id ";
47 if($data['status']) {
48 $query .= " LEFT JOIN combination_form AS cf ON cf.encounter = fe.encounter ";
51 $query .= " WHERE 1=1 ";
53 if($data['status'] == "signed") {
54 $query .= " AND cf.encounter IS NOT NULL AND cf.encounter !=''";
57 if($data['status'] == "unsigned") {
58 $query .= " AND (cf.encounter IS NULL OR cf.encounter ='')";
61 if($data['from_date'] && $data['to_date']) {
62 $query .= " AND fe.date BETWEEN ? AND ? ";
63 $query_data[] = $data['from_date'];
64 $query_data[] = $data['to_date'];
67 if($data['pid']) {
68 $query .= " AND (fe.pid = ? OR pd.fname like ? OR pd.mname like ? OR pd.lname like ? OR CONCAT_WS(' ',pd.fname,pd.lname) like ?) ";
69 $query_data[] = $data['pid'];
70 $query_data[] = "%".$data['pid']."%";
71 $query_data[] = "%".$data['pid']."%";
72 $query_data[] = "%".$data['pid']."%";
73 $query_data[] = "%".$data['pid']."%";
76 if($data['encounter']) {
77 $query .= " AND fe.encounter = ? ";
78 $query_data[] = $data['encounter'];
81 $query .= " GROUP BY fe.pid ";
83 $query .= " ORDER BY fe.pid, fe.date ";
85 $appTable = new ApplicationTable();
87 if($getCount){
88 $res = $appTable->zQuery($query, $query_data);
89 $resCount = $res->count();
90 return $resCount;
93 $query .= " LIMIT " . \Application\Plugin\CommonPlugin::escapeLimit($data['limit_start']) . "," . \Application\Plugin\CommonPlugin::escapeLimit($data['results']);
94 $resDetails = $appTable->zQuery($query, $query_data);
95 return $resDetails;
98 public function getStatus($data)
100 foreach($data as $row){
101 if($pid) $pid .= ',';
102 $pid .= $row['pid'];
104 if(!$pid) $pid = "''";
105 $query = "SELECT cc.*, DATE(fe.date) AS dos, CONCAT_WS(' ',u.fname, u.mname, u.lname) AS user_name FROM ccda AS cc
106 LEFT JOIN form_encounter AS fe ON fe. pid = cc.pid AND fe.encounter = cc.encounter
107 LEFT JOIN users AS u ON u.id = cc.user_id
108 WHERE cc.pid in (?) ORDER BY cc.pid, cc.time desc";
109 $appTable = new ApplicationTable();
110 $result = $appTable->zQuery($query, array($pid));
111 return $result;
114 public function convert_to_yyyymmdd($date)
116 $date = str_replace('/','-',$date);
117 $arr = explode('-',$date);
118 $formatted_date = $arr[2]."-".$arr[0]."-".$arr[1];
119 return $formatted_date;
123 * Convert date from database format to required format
125 * @param String $date Date from database (format: YYYY-MM-DD)
126 * @param String $format Required date format
128 * @return String $formatted_date New formatted date
130 public function date_format($date, $format)
132 if(!$date) return;
133 $format = $format ? $format : 'm/d/y';
134 $temp = explode(' ',$date); //split using space and consider the first portion, incase of date with time
135 $date = $temp[0];
136 $date = str_replace('/','-',$date);
137 $arr = explode('-',$date);
139 if($format == 'm/d/y'){
140 $formatted_date = $arr[1]."/".$arr[2]."/".$arr[0];
142 $formatted_date = $temp[1] ? $formatted_date." ".$temp[1] : $formatted_date; //append the time, if exists, with the new formatted date
143 return $formatted_date;
146 public function getFile($id)
148 $query = "select couch_docid, couch_revid, ccda_data from ccda where id=?";
149 $appTable = new ApplicationTable();
150 $result = $appTable->zQuery($query, array($id));
151 foreach($result as $row){
152 if($row['couch_docid'] != ''){
153 $couch = new CouchDB();
154 $data = array($GLOBALS['couchdb_dbase'], $row['couch_docid']);
155 $resp = $couch->retrieve_doc($data);
156 $content = base64_decode($resp->data);
158 else if(!$row['couch_docid']){
159 $fccda = fopen($row['ccda_data'], "r");
160 $content = fread($fccda, filesize($row['ccda_data']));
161 fclose($fccda);
163 else{
164 $content = $row['ccda_data'];
166 return $content;
171 * Connect to a phiMail Direct Messaging server and transmit
172 * a CCDA document to the specified recipient. If the message is accepted by the
173 * server, the script will return "SUCCESS", otherwise it will return an error msg.
174 * @param DOMDocument ccd the xml data to transmit, a CCDA document is assumed
175 * @param string recipient the Direct Address of the recipient
176 * @param string requested_by user | patient
177 * @return string result of operation
179 public function transmitCCD($data = array())
181 $appTable = new ApplicationTable();
182 $ccda_combination = $data['ccda_combination'];
183 $recipients = $data['recipients'];
184 $xml_type = $data['xml_type'];
185 $rec_arr = explode(";",$recipients);
186 $d_Address = '';
187 foreach($rec_arr as $recipient) {
188 $config_err = "Direct messaging is currently unavailable."." EC:";
189 if ($GLOBALS['phimail_enable']==false) return("$config_err 1");
190 $fp = \Application\Plugin\Phimail::phimail_connect($err);
191 if ($fp===false) return("$config_err $err");
192 $phimail_username = $GLOBALS['phimail_username'];
193 $phimail_password = $GLOBALS['phimail_password'];
194 $ret = \Application\Plugin\Phimail::phimail_write_expect_OK($fp,"AUTH $phimail_username $phimail_password\n");
195 if($ret!==TRUE) return("$config_err 4");
196 $ret = \Application\Plugin\Phimail::phimail_write_expect_OK($fp,"TO $recipient\n");
197 if($ret!==TRUE) {//return("Delivery is not allowed to the specified Direct Address.") ;
198 $d_Address.= ' '.$recipient;
199 continue;
201 $ret=fgets($fp,1024); //ignore extra server data
202 if($requested_by=="patient") {
203 $text_out = "Delivery of the attached clinical document was requested by the patient";
205 else {
206 if(strpos($ccda_combination,'|') !== false) {
207 $text_out = "Clinical documents are attached.";
209 else {
210 $text_out = "A clinical document is attached";
213 $text_len=strlen($text_out);
214 \Application\Plugin\Phimail::phimail_write($fp,"TEXT $text_len\n");
215 $ret=@fgets($fp,256);
216 if($ret!="BEGIN\n") {
217 \Application\Plugin\Phimail::phimail_close($fp);
218 //return("$config_err 5");
219 $d_Address.= ' '.$recipient;
220 continue;
222 $ret=\Application\Plugin\Phimail::phimail_write_expect_OK($fp,$text_out);
223 if($ret!==TRUE) {
224 //return("$config_err 6");
225 $d_Address.= $recipient;
226 continue;
228 $elec_sent = array();
229 $arr = explode('|',$ccda_combination);
230 foreach($arr as $value) {
231 $query = "SELECT id FROM ccda WHERE pid = ? ORDER BY id DESC LIMIT 1";
232 $result = $appTable->zQuery($query, array($value));
233 foreach($result as $val) {
234 $ccda_id = $val['id'];
237 $refs = $appTable->zQuery("select t.id as trans_id from ccda c inner join transactions t on (t.pid = c.pid and t.date = c.updated_date) where c.pid = ? and c.emr_transfer = 1 and t.title = 'LBTref'",array($value));
238 if($refs->count() == 0){
239 $trans = $appTable->zQuery("select id from transactions where pid = ? and title = 'LBTref' order by id desc limit 1",array($value));
240 $trans_cur = $trans->current();
241 $trans_id = $trans_cur['id'] ? $trans_cur['id'] : 0;
243 else{
244 foreach($refs as $r){
245 $trans_id = $r['trans_id'];
248 $elec_sent[] = array('pid' => $value,'map_id' => $trans_id);
250 $ccda = $this->getFile($ccda_id);
252 $xml = simplexml_load_string($ccda);
253 $xsl = new \DOMDocument;
254 $xsl->load(dirname(__FILE__).'/../../../../../public/xsl/ccda.xsl');
255 $proc = new \XSLTProcessor;
256 $proc->importStyleSheet($xsl); // attach the xsl rules
257 $outputFile = sys_get_temp_dir() . '/out_'.time().'.html';
258 $proc->transformToURI($xml, $outputFile);
259 $htmlContent = file_get_contents($outputFile);
260 if($xml_type == 'html') {
261 $ccda_file = htmlspecialchars_decode($htmlContent);
263 elseif($xml_type == 'pdf') {
264 $dompdf = new DOMPDF();
265 $dompdf->load_html($htmlContent);
266 $dompdf->render();
267 //$dompdf->stream();
268 $ccda_file = $dompdf->output();
270 elseif($xml_type == 'xml') {
271 $ccda_file = $ccda;
273 //get patient name in Last_First format (used for CCDA filename)
274 $sql = "SELECT pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS FROM patient_data WHERE pid = ?";
275 $result = $appTable->zQuery($sql, array($value));
276 foreach($result as $val) {
277 $patientData[0] = $val;
279 if (empty($patientData[0]['lname'])) {
280 $att_filename = "";
281 $patientName2 = "";
283 else {
284 //spaces are the argument delimiter for the phiMail API calls and must be removed
285 $extension = $xml_type == 'CCDA' ? 'xml' : strtolower($xml_type);
286 $att_filename = " " . str_replace(" ", "_", $xml_type . "_" . $patientData[0]['lname'] . "_" . $patientData[0]['fname']) . "." . $extension;
287 $patientName2 = $patientData[0]['fname'] . " " . $patientData[0]['lname'];
289 if(strtolower($xml_type) == 'xml') {
290 $ccda = simplexml_load_string($ccda_file);
291 $ccda_out = $ccda->saveXml();
292 $ccda_len = strlen($ccda_out);
293 \Application\Plugin\Phimail::phimail_write($fp,"ADD " . ($xml_type=="CCR" ? $xml_type . ' ' : "CDA ") . $ccda_len . $att_filename . "\n");
295 else if(strtolower($xml_type) == 'html' || strtolower($xml_type) == 'pdf') {
296 $ccda_out = $ccda_file;
297 $message_length = strlen($ccda_out);
298 $add_type = (strtolower($xml_type) == 'html') ? 'TEXT' : 'RAW';
299 \Application\Plugin\Phimail::phimail_write($fp, "ADD " . $add_type . " " . $message_length . "" . $att_filename . "\n");
301 $ret=fgets($fp,256);
302 if($ret!="BEGIN\n") {
303 \Application\Plugin\Phimail::phimail_close($fp);
304 //return("$config_err 7");
305 $d_Address.= ' '.$recipient;
306 continue;
308 $ret=\Application\Plugin\Phimail::phimail_write_expect_OK($fp,$ccda_out);
310 if($ret!==TRUE) {
311 // return("$config_err 8");
312 $d_Address.= ' '.$recipient;
313 continue;
315 \Application\Plugin\Phimail::phimail_write($fp,"SEND\n");
316 $ret=fgets($fp,256);
317 //"INSERT INTO `amc_misc_data` (`amc_id`,`pid`,`map_category`,`map_id`,`date_created`) VALUES(?,?,?,?,NOW())"
318 \Application\Plugin\Phimail::phimail_close($fp);
320 if($d_Address == '') {
322 foreach ($elec_sent as $elec){
323 $appTable->zQuery("INSERT into amc_misc_data(amc_id,pid,map_category,map_id,date_created,date_completed) values('send_sum_amc',?,'transactions',?,NOW(),NOW())",array($elec['pid'],$elec['map_id']));
324 $appTable->zQuery("INSERT into amc_misc_data(amc_id,pid,map_category,map_id,date_created,date_completed) values('send_sum_elec_amc',?,'transactions',?,NOW(),NOW())",array($elec['pid'],$elec['map_id']));
327 return("Successfully Sent");
329 else {
330 return("Delivery is not allowed to:".$d_Address);
333 public function getFileID($pid)
335 $appTable = new ApplicationTable();
336 $query = "SELECT cc.id, pd.fname, pd.lname, pd.pid FROM ccda AS cc
337 LEFT JOIN patient_data AS pd ON pd.pid=cc.pid
338 WHERE cc.pid = ?
339 ORDER BY cc.id DESC LIMIT 1";
340 $res = $appTable->zQuery($query,array($pid));
341 $res_cur = $res->current();
342 return $res_cur;
346 * Save new user with abook type emr_direct
348 * @param String first name
349 * @param String last name
350 * @param String direct address
353 public function AddNewUSer($data = array())
355 $fname = $data['fname'];
356 $lname = $data['lname'];
357 $direct_address = $data['direct_address'];
358 $appTable = new ApplicationTable();
359 $query = "INSERT INTO users SET username = ? ,password = ? ,authorized = ?,fname = ?,lname = ?,email = ?,active = ?,abook_type = ?";
360 $appTable->zQuery($query,array('','',0,$fname,$lname,$direct_address,1,'emr_direct'));