response = array("status" => "ERR", "message" => ""); $this->load->library('ImageManipulator'); } function reply($compress = true) { if ($compress) { echo gzdeflate(json_encode($this->response)); exit; } echo json_encode($this->response); } function get_one_row($sql, $param = false) { list($status, $msg) = $this->get_rows($sql . " limit 0,1 ", $param); if ($status == -1) return array($status, $msg); if (count($msg) == 0) return array(0, array()); return array(1, $msg[0]); } function get_rows($sql, $param = false) { if ($param) { $qry = $this->db->query($sql, $param); } else { $qry = $this->db->query($sql); } if (!$qry) { return array(-1, $this->db->error()["message"] . "|" . $this->db->last_query()); } return array(0, $qry->result_array()); } function exec_query($sql, $param = false) { if ($param) { $qry = $this->db->query($sql, $param); } else { $qry = $this->db->query($sql); } if (!$qry) { return array(false, $this->db->error()["message"] . "|" . $this->db->last_query()); } return array(true, ""); } function log($msg) { return date("Y-m-d H:i:s") . " " . $msg . "\n"; } function photo($mcuPrepareCode) { $log_message = $this->log("Start Download Photo : MCU Prepare Code {$mcuPrepareCode}"); $sql = "select McuOfflinePrepareID from mcu_offline_prepare where McuOfflinePrepareCode=? and McuOfflinePrepareIsActive = 'Y'"; list($status, $msg) = $this->get_one_row($sql, array($mcuPrepareCode)); if ($status == -1) { $log_message .= $this->log("Get McuOfflinePrepare : " . $msg); echo $log_message; return; } $mcuPrepareID = $msg["McuOfflinePrepareID"]; $sql = "select M_BranchCode from m_branch where M_BranchIsActive ='Y' and M_BranchIsDefault='Y'"; list($status, $msg) = $this->get_one_row($sql); if ($status == -1) { $log_message .= $this->log("Get Default Branch : " . $msg); echo $log_message; return; } $param = json_encode(array( "branchCode" => $msg["M_BranchCode"], "mcuPrepareCode" => $mcuPrepareCode )); $result = $this->post("https://admin.subcon.pramita.co.id/one-api/subcon/R_download_subcon/photo", $param); if ($result["status"] != "OK") { $log_message .= $this->log("Error Download Photo : " . $result["message"]); echo $log_message; return; } $log_message .= $this->log(" Download Photo : " . count($result["files"])); $tot_upload = 0; foreach ($result["files"] as $file) { $resp = $this->post_photo($file["id"], $file["data"]); if ($resp["status"] != "OK") { $log_message .= $this->log("Error upload photo for Patient ID " . $file["id"]); } else { $tot_upload++; } } $log_message .= $this->log(" Upload Photo : {$tot_upload} "); echo $log_message; return; } function uncompress() { $LIMIT_ORDER = 5; $sql = "select * from subcon_download where subConDownloadIsActive='Y' and subConDownloadStatus='N' limit 0,$LIMIT_ORDER"; list($status, $msg) = $this->get_rows($sql); if ($status == -1) { $log_message .= $this->log(" Error : {$msg}"); echo $log_message; unlink("/xtmp/subcon_generate_order.pid"); exit; } $rows = $msg; $total_order_generated = 0; foreach ($rows as $r) { $this->db->trans_begin(); $subconDownloadID = $r["subconDownloadID"]; $gz_data = $r["subconDownloadJsonGz"]; $data = gzinflate($gz_data); $order = json_decode($data, true); $log_message = ""; if (json_last_error() != JSON_ERROR_NONE) { $log_message .= $this->log(" Err Decode Json | " . json_last_error_msg() . "| " . $data); $this->db->trans_rollback(); continue; } echo "$subconDownloadID \n"; print_r($order); echo "\n"; } } function generate_order() { $SUBCON_USER_ID = 1500; // -> Regonline User ID juga $log_message = ""; echo $this->log("Start Generate Order"); if (file_exists("/xtmp/subcon_generate_order.pid")) { $date = file_get_contents("/xtmp/subcon_generate_order.pid"); $diff_hour = (strtotime(date("Y-m-d H:i:s")) - strtotime($date)) / 3600; if ($diff_hour >= 1) { unlink("/xtmp/subcon_generate_order.pid"); } else { $log_message .= $this->log(" Subcon Generate Order Still Running"); echo $log_message; exit; } } file_put_contents("/xtmp/subcon_generate_order.pid", date("Y-m-d H:i:s")); $LIMIT_ORDER = 5; $sql = "select * from subcon_download where subConDownloadIsActive='Y' and subConDownloadStatus='N' limit 0,$LIMIT_ORDER"; list($status, $msg) = $this->get_rows($sql); if ($status == -1) { $log_message .= $this->log(" Error : {$msg}"); echo $log_message; unlink("/xtmp/subcon_generate_order.pid"); exit; } $rows = $msg; $total_order_generated = 0; $log_message = ""; foreach ($rows as $r) { $this->db->trans_begin(); $subconDownloadID = $r["subconDownloadID"]; $gz_data = $r["subconDownloadJsonGz"]; $data = gzinflate($gz_data); $order = json_decode($data, true); echo $this->log("Order : " . $order["T_OrderHeaderLabNumber"]); if (json_last_error() != JSON_ERROR_NONE) { echo $this->log(" Err Decode Json | " . json_last_error_msg() . "| " . $data); $this->db->trans_rollback(); continue; } //TODO: 1 Insert into OrderHeader get new T_OrderHead); $header = array_filter($order, function ($f) { if (strpos($f, "T_OrderHeader") !== false) { return true; } return false; }, ARRAY_FILTER_USE_KEY); $orgT_OrderHeaderLabNumber = $order["T_OrderHeaderLabNumber"]; $header["T_OrderHeaderUserID"] = $SUBCON_USER_ID; unset($header["T_OrderHeaderID"]); $qry = $this->db->insert("t_orderheader", $header); if (!$qry) { echo $this->log("Err Insert Header " . $this->db->error()["message"] . "|" . $this->db->last_query()); $this->db->trans_rollback(); continue; } $newT_OrderHeaderID = $this->db->insert_id(); if (isset($order["patient"]["M_PatientID"])) { echo $this->log(" New Patient : {$order['patient']['M_PatientNoReg']}"); $sql = "select M_PatientID from m_patient where M_PatientIsActive = 'Y' and M_PatientNoReg=?"; list($status, $msg) = $this->get_one_row($sql, array($order["patient"]["M_PatientNoReg"])); if ($status == -1) { echo $this->log("Err Check New Patient " . $this->db->error()["message"] . "|" . $this->db->last_query()); $this->db->trans_rollback(); continue; } if ($status == 0) { //new patient $o_p = $order["patient"]; $p_a = $o_p["address"]; unset($o_p["address"]); unset($o_p["T_OrderHeaderID"]); unset($o_p["M_PatientID"]); $data_photo = ""; if (isset($o_p["data"]) && strlen($o_p["data"]) > 100) { $data_photo = $o_p["data"]; } unset($o_p["data"]); if (isset($o_p["data_thumb"])) unset($o_p["data_thumb"]); $qry = $this->db->insert("m_patient", $o_p); if (!$qry) { echo $this->log("Err Insert New Patient " . $this->db->error()["message"] . "|" . $this->db->last_query()); $this->db->trans_rollback(); continue; } $newPatientID = $this->db->insert_id(); if ($data_photo != "") { echo $this->log("Upload Photo $newPatientID | " . strlen($data_photo)); $resp = $this->post_photo($newPatientID, $data_photo, $o_p["M_PatientNoReg"]); if ($resp["status"] == "OK") { echo $this->log(" New Photo Uploaded | $newPatientID | " . strlen($data_photo)); } else { echo $this->log("Err Upload New Photo " . $resp["message"]); $this->db->trans_rollback(); continue; } } else { } $p_a["M_PatientAddressM_PatientID"] = $newPatientID; unset($p_a["M_PatientAddressID"]); $qry = $this->db->insert("m_patientaddress", $p_a); if (!$qry) { echo $this->log("Err Insert New Patient Address " . $this->db->error()["message"] . "|" . $this->db->last_query()); $this->db->trans_rollback(); continue; } } else { $newPatientID = $msg["M_PatientID"]; } $sql = "update t_orderheader set T_OrderHeaderM_PatientID=? where T_OrderHeaderID=?"; $qry = $this->db->query($sql, array($newPatientID, $newT_OrderHeaderID)); if (!$qry) { echo $this->log("Err Insert Update T_OrderHeaderM_PatientID " . $this->db->error()["message"] . "|" . $this->db->last_query()); $this->db->trans_rollback(); continue; } } $sql = "select * from t_orderheader where T_OrderHeaderID=?"; list($status, $new_header) = $this->get_one_row($sql, array($newT_OrderHeaderID)); if ($status == -1) { echo $this->log("ERR Select Order Header : " . $new_header); $this->db->trans_rollback(); continue; } $newT_OrderHeaderLabNumber = $new_header["T_OrderHeaderLabNumber"]; $newT_OrderHeaderDate = $new_header["T_OrderHeaderDate"]; //promises $promises = $order["promises"]; $map_promises = array(); $promise_have_error = false; foreach ($promises as $p) { $p["T_OrderPromiseT_OrderHeaderID"] = $newT_OrderHeaderID; $orgPromiseID = $p["T_OrderPromiseID"]; unset($p["T_OrderPromiseID"]); $qry = $this->db->insert("t_orderpromise", $p); if (!$qry) { echo $this->log("Err Insert Promise " . $this->db->error()["message"] . "|" . $this->db->last_query()); $this->db->trans_rollback(); $promise_have_error = true; break; } $map_promises[$orgPromiseID] = $this->db->insert_id(); } if ($promise_have_error) { continue; } //details $odetails = $order["details"]; $details = array_map(function ($d) use ($newT_OrderHeaderID) { $d["T_OrderDetailT_OrderHeaderID"] = $newT_OrderHeaderID; return $d; }, $odetails); $details_have_error = false; foreach ($details as $d) { $det_only = array_filter($d, function ($f) { if (strpos($f, "T_OrderDetail") !== false) { return true; } return false; }, ARRAY_FILTER_USE_KEY); $det_only["T_OrderDetailUserID"] = $SUBCON_USER_ID; unset($det_only["T_OrderDetailID"]); if (isset($map_promises[$det_only["T_OrderDetailT_OrderPromiseID"]])) { $det_only["T_OrderDetailT_OrderPromiseID"] = $map_promises[$det_only["T_OrderDetailT_OrderPromiseID"]]; } $qry = $this->db->insert("t_orderdetail", $det_only); if (!$qry) { echo $this->log("Err Insert Detail " . $this->db->error()["message"] . "|" . $this->db->last_query()); $this->db->trans_rollback(); $details_have_error = true; break; } $newT_OrderDetailID = $this->db->insert_id(); $det_addon = $d["addons"]; $det_addon["T_OrderDetailAddOnT_OrderDetailID"] = $newT_OrderDetailID; unset($det_addon["T_OrderDetailAddOnID"]); $qry = $this->db->insert("t_orderdetailaddon", $det_addon); if (!$qry) { echo $this->log("Err Insert Detail AddOn " . $this->db->error()["message"] . "|" . $this->db->last_query()); $this->db->trans_rollback(); $details_have_error = true; break; } } if ($details_have_error) continue; //addons $addon = $order["addons"]; unset($addon["T_OrderHeaderAddOnID"]); $addon["T_OrderHeaderAddOnT_OrderHeaderID"] = $newT_OrderHeaderID; $addon["T_OrderHeaderAddOnLabNumberOrigin"] = $orgT_OrderHeaderLabNumber; $addon["T_OrderHeaderAddOnUserID"] = $SUBCON_USER_ID; $qry = $this->db->insert("t_orderheaderaddon", $addon); if (!$qry) { echo $this->log("Err Insert T_OrderHeaderAddOn " . $this->db->error()["message"] . "|" . $this->db->last_query()); $this->db->trans_rollback(); continue; } //deliveries $deliveries = $order["deliveries"]; $deliveries_have_error = false; foreach ($deliveries as $d) { $deliv = array_filter($d, function ($f) { if (strpos($f, "T_OrderDetail") !== false) { return true; } return false; }, ARRAY_FILTER_USE_KEY); unset($deliv["T_OrderDeliveryID"]); $deliv["T_OrderDeliveryT_OrderHeaderID"] = $newT_OrderHeaderID; $deliv["T_OrderDeliveryUserID"] = $SUBCON_USER_ID; $qry = $this->db->insert("t_orderdelivery", $deliv); if (!$qry) { echo $this->log("Err Insert T_OrderDelivery " . $this->db->error()["message"] . "|" . $this->db->last_query()); $this->db->trans_rollback(); $deliveries_have_error = true; } $newT_OrderDeliveryID = $this->db->insert_id(); //TODO: delivery note } if ($deliveries_have_error) continue; //fo_vers $fo_vers = $order["fo_vers"]; $fo_vers_have_error = false; foreach ($fo_vers as $fo_ver) { unset($fo_ver["Fo_VerificationsValueID"]); $fo_ver["Fo_VerificationsValueT_OrderHeaderID"] = $newT_OrderHeaderID; $fo_ver["Fo_VerificationsValueUserID"] = $SUBCON_USER_ID; $qry = $this->db->insert("fo_verificationsvalue", $fo_ver); if (!$qry) { echo $this->log("Err Insert Fo verification value " . $this->db->error()["message"] . "|" . $this->db->last_query()); $this->db->trans_rollback(); $fo_vers_have_error = true; break; } } if ($fo_vers_have_error) continue; //barcodes $barcodes = $order["barcodes"]; $map_barcode = array(); $barcode_have_error = false; foreach ($barcodes as $b) { $orgBarcodeID = $b["T_BarcodeLabID"]; unset($b["T_BarcodeLabID"]); $b["T_BarcodeLabT_OrderHeaderID"] = $newT_OrderHeaderID; $b["T_BarcodeLabUserID"] = $SUBCON_USER_ID; $qry = $this->db->insert("t_barcodelab", $b); if (!$qry) { echo $this->log("Err Insert t_barcodelab value " . $this->db->error()["message"] . "|" . $this->db->last_query()); $this->db->trans_rollback(); $barcode_have_error = true; break; } $newBarcodeID = $this->db->insert_id(); $map_barcode[$orgBarcodeID] = $newBarcodeID; } if ($barcode_have_error) continue; //samples $samples = $order["samples"]; $samples_have_error = false; foreach ($samples as $s) { unset($s["T_OrderSampleID"]); $s["T_OrderSampleT_OrderHeaderID"] = $newT_OrderHeaderID; if (isset($map_barcode[$s["T_OrderSampleT_BarcodeLabID"]])) { $s["T_OrderSampleT_BarcodeLabID"] = $map_barcode[$s["T_OrderSampleT_BarcodeLabID"]]; } $s["T_OrderSampleSamplingUserID"] = $SUBCON_USER_ID; $s["T_OrderSampleReceiveUserID"] = $SUBCON_USER_ID; $s["T_OrderSampleVerificationUserID"] = $SUBCON_USER_ID; $s["T_OrderSampleSendHandlingUserID"] = $SUBCON_USER_ID; $s["T_OrderSampleHandlingUserID"] = $SUBCON_USER_ID; $s["T_OrderSampleReceiveHandlingUserID"] = $SUBCON_USER_ID; $s["T_OrderSampleProcessingUserID"] = $SUBCON_USER_ID; $s["T_OrderSampleUserID"] = $SUBCON_USER_ID; $s["T_OrderSampleWorklistReceiveUserID"] = $SUBCON_USER_ID; $sql = "select T_OrderSampleID from t_ordersample where T_OrderSampleT_OrderHeaderID=? and T_OrderSampleT_BarcodeLabID= ? and T_OrderSampleT_SampleTypeID=?"; list($status, $existing) = $this->get_one_row( $sql, array( $s["T_OrderSampleT_OrderHeaderID"], $s["T_OrderSampleT_BarcodeLabID"], $s["T_OrderSampleT_SampleTypeID"] ) ); if ($status == -1) { echo $this->log("Err Check t_ordersample value " . $this->db->error()["message"] . "|" . $this->db->last_query()); $this->db->trans_rollback(); $samples_have_error = true; break; } if ($status == 1) continue; $qry = $this->db->insert("t_ordersample", $s); if (!$qry) { echo $this->log("Err Insert t_ordersample value " . $this->db->error()["message"] . "|" . $this->db->last_query()); $this->db->trans_rollback(); $samples_have_error = true; break; } } if ($samples_have_error) continue; $sql = "update subcon_download set subconDownloadT_OrderHeaderID = ? , subconDownloadStatus = 'Y' where subconDownloadID = ? "; $qry = $this->db->query($sql, array($newT_OrderHeaderID, $subconDownloadID)); if (!$qry) { echo $this->log("Err Update t_orderheader " . $this->db->error()["message"] . "|" . $this->db->last_query()); $this->db->trans_rollback(); continue; } //update T_OrderHeaderAddOnLabNumberOrigin $sql = "update t_orderheaderaddon set T_OrderHeaderAddOnLabNumberOrigin=? where T_OrderHeaderAddOnT_OrderHeaderID = ?"; $qry = $this->db->query($sql, array( $orgT_OrderHeaderLabNumber, $newT_OrderHeaderID )); if (!$qry) { echo $this->log("Err Update Orgin Lab Number " . $this->db->error()["message"] . "|" . $this->db->last_query()); $this->db->trans_rollback(); continue; } $this->db->trans_commit(); echo $this->log(" Order {$orgT_OrderHeaderLabNumber} => {$newT_OrderHeaderLabNumber} on {$newT_OrderHeaderDate} "); echo $this->log(" Sleep for 5s"); sleep(5); } if ($log_message != "") echo $log_message; unlink("/xtmp/subcon_generate_order.pid"); } function get_mcu_code() { $log_message = ""; $sql = "select M_BranchCode from m_branch where M_BranchIsActive ='Y' and M_BranchIsDefault='Y'"; list($status, $msg) = $this->get_one_row($sql); if ($status == -1) { $log_message .= $this->log("Get Default Branch : " . $msg); echo $log_message; exit; } $log_message .= $this->log("Get MCu Prepare for Branch : " . $msg["M_BranchCode"]); echo $log_message; $param = json_encode(array( "branchCode" => $msg["M_BranchCode"] )); $result = $this->post("https://admin.subcon.pramita.co.id/one-api/subcon/R_download_subcon/get_mcu", $param); if ($result["status"] != "OK") { $log_message .= $this->log("Start Download SubCon : MCU Prepare Code {$mcuPrepareCode}"); echo $log_message . "\n"; exit; } $mcu = $result["data"]; return $mcu; } function download() { $log_message = ""; if (file_exists("/xtmp/subcon_download.pid")) { $date = file_get_contents("/xtmp/subcon_download.pid"); $diff_hour = (strtotime(date("Y-m-d H:i:s")) - strtotime($date)) / 3600; if ($diff_hour >= 1) { unlink("/xtmp/subcon_download.pid"); } else { $log_message .= $this->log(" Subcon Downloader Still Running"); echo $log_message; exit; } } file_put_contents("/xtmp/subcon_download.pid", date("Y-m-d H:i:s")); $arr_mcu = $this->get_mcu_code(); foreach ($arr_mcu as $mcuCode) { $this->download_org($mcuCode); } unlink("/xtmp/subcon_download.pid"); } function download_org($mcuPrepareCode) { $log_message = $this->log("Start Download SubCon : MCU Prepare Code {$mcuPrepareCode}"); $sql = "select McuOfflinePrepareID from mcu_offline_prepare where McuOfflinePrepareCode=? and McuOfflinePrepareIsActive = 'Y'"; list($status, $msg) = $this->get_one_row($sql, array($mcuPrepareCode)); if ($status == -1) { $log_message .= $this->log("Get McuOfflinePrepare : " . $msg); echo $log_message; return; } $mcuPrepareID = $msg["McuOfflinePrepareID"]; $sql = "select M_BranchCode from m_branch where M_BranchIsActive ='Y' and M_BranchIsDefault='Y'"; list($status, $msg) = $this->get_one_row($sql); if ($status == -1) { $log_message .= $this->log("Get Default Branch : " . $msg); echo $log_message; return; } $param = json_encode(array( "branchCode" => $msg["M_BranchCode"], "mcuPrepareCode" => $mcuPrepareCode )); $result = $this->post("https://admin.subcon.pramita.co.id/one-api/subcon/R_download_subcon", $param); if ($result["status"] != "OK") { $log_message .= $this->log("Start Download SubCon : MCU Prepare Code {$mcuPrepareCode}"); echo $log_message . "\n"; print_r($result); return; } $this->db->trans_begin(); $ids = $result["sucontractor_download"]; $order_ids = array(); foreach ($result["data"] as $order) { $j_order = json_encode($order); $gzData = gzdeflate($j_order, 9); if (json_last_error() != JSON_ERROR_NONE) { $log_message .= $this->log("Error Json Encode | " . json_last_error_msg()); $this->db->trans_rollback(); $log_message .= $this->log(" Reset SubContractorDownload IDS : " . implode(",", $ids)); $this->reset_order($ids); echo $log_message; return; } $order_data = array( "subconDownloadJsonGz" => $gzData, "subconDownloadMcuOfflinePrepareCode" => $mcuPrepareCode, "subconDownloadMcuOfflinePrepareID" => $mcuPrepareID, "subconDownloadOriginT_OrderHeaderID" => $order["T_OrderHeaderID"] ); $order_ids[] = $order["T_OrderHeaderID"]; $qry = $this->db->insert("subcon_download", $order_data); if (!$qry) { $log_message .= $this->log("Error Save Download Data : " . $this->db->error()["message"] . " | " . $this->db->last_query()); $this->db->trans_rollback(); $log_message .= $this->log(" Reset SubContractorDownload IDS : " . implode(",", $ids)); $this->reset_order($ids); echo $log_message; return; } } $this->db->trans_commit(); $log_message .= $this->log("Download " . count($ids) . " orders."); echo $log_message; if (count($ids) > 0) { $this->photo($mcuPrepareCode); } return; } function reset_order($ids) { $log_message = $this->log("Start Reset SubCon : IDS {implode(',',$ids)}"); $param = json_encode(array( "ids" => $ids )); $result = $this->post("https://admin.subcon.pramita.co.id/one-api/subcon/R_download_subcon/reset", $param); if ($result["status"] == "OK") { $log_message .= $this->log("Start Reset SubCon : Success"); } else { $log_message .= $this->log("Start Reset SubCon : Error | {$result['message']}"); } } function post_photo($id, $data, $no_reg = "") { $url = "http://localhost/one-api/subcon/download_subcon/upload"; $xdata = json_encode(array("id" => $id, "data" => $data, "no_reg" => $no_reg)); $zdata = gzdeflate($xdata, 9); $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $zdata); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/octet', 'Content-Length: ' . strlen($zdata) )); $result = curl_exec($ch); $msg = curl_error($ch); curl_close($ch); if ($msg != "") { return array( "status" => "ERR", "message" => $msg ); } $j_result = json_decode($result, true); if (json_last_error() != JSON_ERROR_NONE) { return array( "status" => "ERR", "message" => "Invalid JSON | " . $result . "|" . json_last_error_msg() ); } return $j_result; } function post($url, $data) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_TIMEOUT, 120); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data) )); $z_result = curl_exec($ch); $msg = curl_error($ch); curl_close($ch); if ($msg != "") { return array( "status" => "ERR", "message" => $msg ); } $result = gzinflate($z_result); if (!$result) { return array( "status" => "ERR", "message" => "Invalid Compressed | " . $z_result ); } $j_result = json_decode($result, true); if (json_last_error() != JSON_ERROR_NONE) { return array( "status" => "ERR", "message" => "Invalid JSON | " . $result . "|" . json_last_error_msg() ); } return $j_result; } public function upload() { $zdata = file_get_contents("php://input"); $data = gzinflate($zdata); $inp = json_decode($data, true); $home_dir = "/home/one/project/one/"; $target_dir = $home_dir . "one-media/one-photo/patient/" . date("Y") . "/"; $y = $this->regenerateOldPhoto($home_dir, $inp['id']); // get patient mr if ($inp["no_reg"] == "") { $sql = "Select M_PatientNoReg from m_patient where M_PatientID = ? and M_PatientIsActive = 'Y'"; list($resp, $msg) = $this->get_one_row($sql, array($inp["id"])); if ($resp == -1) { $this->response["message"] = $msg; echo json_encode($this->response); exit; } if ($resp == 0) { $this->response["message"] = "Error Patient Not Found " . $inp["id"]; echo json_encode($this->response); exit; } $p = $msg; $patientNoreg = $p["M_PatientNoReg"]; } else { $patientNoreg = $inp["no_reg"]; } if (!file_exists($target_dir)) { mkdir($target_dir, 0755, true); } $target_path = $target_dir . $patientNoreg . ".jpg"; $this->base64_to_jpeg($inp['data'], $target_path); // CROP Image $im = new ImageManipulator($target_path); $w = $im->getWidth(); $h = $im->getHeight(); $mw = ceil(3 * $h / 4); if ($w <= $mw) { $x1 = 0; $y1 = 0; $x2 = $w; $y2 = $h; } else { $x1 = floor(($w - $mw) / 2); $y1 = 0; $x2 = ceil($w - (($w - $mw) / 2)); $y2 = $h; } $im->crop($x1, $y1, $x2, $y2); // takes care of out of boundary conditions automatically $im->save($target_path); $x = $this->generateThumbnail($target_path, 75, 100); // Save to DB if ($inp["no_reg"] == "") { $this->db->set("M_PatientPhoto", "/" . str_replace($home_dir, "", $target_path)) ->set("M_PatientPhotoThumb", "/" . str_replace($home_dir, "", $x)) ->set('M_PatientPhotoCounter', '`M_PatientPhotoCounter` + 1', false) ->where('M_PatientID', $inp['id']) ->update('m_patient'); } // LOGGING $code = $y ? "PHOTO.PATIENT.EDIT" : "PHOTO.PATIENT.ADD"; $one_log = $this->load->database('onelog', true); $one_log->set('Log_PhotoCode', $code) ->set('Log_PhotoM_PatientID', $inp['id']) ->set('Log_PhotoUrl', $y ? $y : "/" . str_replace($home_dir, "", $target_path)) ->insert('log_photo'); $this->sys_ok(["rename" => $y, "patient_id" => $inp['id'], "patient_mr" => $p->M_PatientNoReg, "photo_url" => "http://" . $_SERVER['SERVER_NAME'] . "/" . str_replace($home_dir, "", $target_path) . "?d=" . date("YmdHis")]); } function base64_to_jpeg($base64_string, $output_file) { $ifp = fopen($output_file, 'wb'); //$data = explode(',', $base64_string); fwrite($ifp, base64_decode($base64_string)); fclose($ifp); return $output_file; } function generateThumbnail($img, $width, $height, $quality = 90) { if (is_file($img)) { $imagick = new Imagick(realpath($img)); $imagick->setImageFormat('jpeg'); $imagick->setImageCompression(Imagick::COMPRESSION_JPEG); $imagick->setImageCompressionQuality($quality); $imagick->thumbnailImage($width, $height, false, false); $filename_no_ext = reset(explode('.', $img)); if (file_put_contents($filename_no_ext . '_thumb' . '.jpg', $imagick) === false) { throw new Exception("Could not put contents."); } return $filename_no_ext . '_thumb' . '.jpg'; } else { throw new Exception("No valid image provided with {$img}."); } } function regenerateOldPhoto($home_dir, $id) { $r = $this->db->select('m_patientphoto, m_patientphotocounter', false) ->where('m_patientid', $id) ->get('m_patient') ->row(); if ($r->m_patientphoto != null && $r->m_patientphotocounter > 0) { $full_path = substr_replace($home_dir, "", -1) . $r->m_patientphoto; $path_parts = pathinfo($full_path); $rename = $path_parts['dirname'] . '/' . $path_parts['filename'] . '-' . $r->m_patientphotocounter . '.' . $path_parts['extension']; rename($full_path, $rename); return "/" . str_replace($home_dir, "", $rename); } return false; } }