first commit

This commit is contained in:
2024-04-19 14:04:41 +07:00
commit 014283036f
7282 changed files with 1324127 additions and 0 deletions
+351
View File
@@ -0,0 +1,351 @@
<?php
Class Billing {
private $tempatlayanan;
private $nobill;
private $tanggal;
private $shift;
private $nomr;
private $user;
private $idxdaftar;
private $lunas;
private $jmlbayar;
private $ipaddress;
private $carabayar;
private $poliklinik;
private $aps;
private $unit;
private $nonota;
private $tbl_billing;
private $tbl_bayarbilling;
private $col_bill;
private $status_batal;
public function __construct($tempatlayanan,$nomr,$idxdaftar,$tanggal,$lunas, $jmlbayar,$carabayar,$poliklinik,$aps,$unit = 0,$user = '')
{
$this->tanggal = $tanggal;
$this->nomr = $nomr;
$this->shift = (array_key_exists('SHIFT', $_SESSION)) ? $_SESSION['SHIFT'] : 1;
$this->idxdaftar = $idxdaftar;
$this->user = ($_SESSION['NIP'] == '' && $user != '') ? $user : $_SESSION['NIP'];
$this->lunas = $lunas;
$this->jmlbayar = $jmlbayar;
$this->ipaddress = getRealIpAddr();
$this->carabayar = $carabayar;
$this->poliklinik = $poliklinik;
$this->aps = $aps;
$this->unit = $unit;
$this->nonota = lastNoNota();
$this->tempatlayanan = $tempatlayanan;
$this->status_batal = FALSE;
if($this->tempatlayanan == 'irja')
{
$this->tbl_billing = 't_billrajal';
$this->tbl_billingdetil = 't_billrajal_detil';
$this->tbl_bayarbilling = 't_bayarrajal';
$this->col_bill[$this->tbl_billing] = ['kodetarif','nomr','tanggal','shift','nip','qty','idxdaftar','nobill', 'jasa_sarana','jasa_pelayanan','jasa_anastesi','tarifrs','kdpoly','carabayar','aps','kddokter','unit','nonota','tgl_transaksi','kode_ruang'];
$this->col_bill[$this->tbl_bayarbilling] = ['nomr','shift','nip','idxdaftar','nobill',' totjasa_sarana','totjasa_pelayanan','totjasa_anastesi','tottarifrs','carabayar','aps','tglbayar','jambayar','jmbayar','tbp','lunas','status','unit','idxbill'];
}
elseif($this->tempatlayanan == 'irna')
{
$this->tbl_billing = 't_billranap';
$this->tbl_billingdetil = 't_billranap_detil';
$this->tbl_bayarbilling = 't_bayarranap';
$this->col_bill[$this->tbl_billing] = ['kodetarif','nomr','tanggal','shift','nip','qty','idxdaftar','nobill', 'jasa_sarana','jasa_pelayanan','jasa_anastesi','tarifrs','kdpoly','carabayar','aps','kddokter','unit','discount','nott','nonota','tgl_transaksi','kode_ruang'];
$this->col_bill[$this->tbl_bayarbilling] = ['nomr','shift','nip','idxdaftar','nobill',' totjasa_sarana','totjasa_pelayanan','totjasa_anastesi','tottarifrs','carabayar','aps','tglbayar','jambayar','jmbayar','tbp','lunas','status','discount','noruang','nott','tglbilling','idxbill'];
}
elseif($this->tempatlayanan == 'nonregister')
{
$this->tbl_billing = 't_billnonreg';
$this->tbl_billingdetil = 't_billnonreg_detil';
$this->tbl_bayarbilling = 't_bayarnonreg';
$this->col_bill[$this->tbl_billing] = ['kodetarif','no_nonreg','tanggal','shift','nip','qty','idx_nonreg','nobill', 'jasa_sarana','jasa_pelayanan','jasa_anastesi','tarifrs','carabayar','kddokter','unit','nonota','ruang','tgl_transaksi','kode_ruang'];
$this->col_bill[$this->tbl_bayarbilling] = ['no_nonreg','shift','nip','idx_nonreg','nobill',' totjasa_sarana','totjasa_pelayanan','totjasa_anastesi','tottarifrs','carabayar','tglbayar','jambayar','jmbayar','tbp','lunas','status','unit','idxbill'];
}
}
public function simpanBill($nobill = null)
{
if($this->status_batal){
array_push($this->col_bill[$this->tbl_billing],'status');
}
$this->setNobill($nobill);
if($this->nobill != '')
{
$rajal_status = ($this->tempatlayanan == 'irja') ? 1 : (($this->tempatlayanan == 'irna') ? 0 : 2);
$this->nonota = last_nonota_by_bill($this->nobill,$rajal_status);
$result_bill = $this->createBill();
if($result_bill) {
$save_bayar = $this->createBayar();
return $this->nonota;
}
else {
return false;
}
}
else {
return false;
}
}
private function setNobill($nobill = null) {
global $db;
if($this->tempatlayanan == 'nonregister') {
$get_bill = $db->query("SELECT nobill FROM ".$this->tbl_billing." WHERE no_nonreg = '{$this->nomr}' and idx_nonreg = ".$this->idxdaftar." limit 1");
if($get_bill->numRows() > 0) {
$data_bill = $get_bill->fetchFirst();
$this->nobill = $data_bill['nobill'];
}
elseif($nobill != null) {
$this->nobill = $nobill;
}
else {
$PRE_NO = $LASTNOBILL = $xLASTNOBILL = $nomor = null;
$PRE_NO = date('y');
// $PRE_NO = '22';
$sql = $db->query("SELECT nomor FROM m_maxnobill where type = 'bill_nonreg' and SUBSTRING(nomor::varchar(10),1,2) = '".$PRE_NO."'");
if($sql->numRows() > 0){
$row = $sql->fetchAll();
$LASTNOBILL = $row[0]['nomor']; // 18000002
if(substr($LASTNOBILL, 2) == '999999') {
$xLASTNOBILL = '1'.str_pad('0', 6, '0', STR_PAD_LEFT);
}
else {
if(strlen(substr($LASTNOBILL,2)) < 6) {
$xLASTNOBILL = str_pad( (substr($LASTNOBILL,2)+$p), 6, '0', STR_PAD_LEFT);
}
else {
$xLASTNOBILL = str_pad( (substr($LASTNOBILL,2)+$p), strlen(substr($LASTNOBILL,2)), '0', STR_PAD_LEFT);
}
}
$nomor = $PRE_NO.$xLASTNOBILL;
$this->nobill = ($nomor + 1);
}
else {
$this->nobill = $PRE_NO.'000001';
}
// $get_no = $db->query("SELECT nomor from m_maxnobill where type = 'bill_nonreg'");
// $nomor = $get_no->fetchFirst()['nomor'];
// if($nomor == null)
// {
// $this->nobill = date('y').'00000001';
// }
// else {
// $this->nobill = ($nomor + 1);
// }
execute("UPDATE m_maxnobill set nomor = ".$this->nobill." where type = 'bill_nonreg' ");
}
}
else {
$get_bill = $db->query("SELECT nobill FROM ".$this->tbl_billing." WHERE nomr = '{$this->nomr}' and idxdaftar = ".$this->idxdaftar." limit 1");
if($get_bill->numRows() > 0) {
$data_bill = $get_bill->fetchFirst();
$this->nobill = $data_bill['nobill'];
}
elseif($nobill != null) {
$this->nobill = $nobill;
}
else {
$PRE_NO = $LASTNOBILL = $xLASTNOBILL = $nomor = null;
$PRE_NO = date('y');
// $PRE_NO = '22';
$sql = $db->query("SELECT nomor FROM m_maxnobill where type = 'bill_pasien' and SUBSTRING(nomor::varchar(10),1,2) = '".$PRE_NO."'");
if($sql->numRows() > 0){
$row = $sql->fetchAll();
$LASTNOBILL = $row[0]['nomor']; // 18000002
if(substr($LASTNOBILL, 2) == '999999') {
$xLASTNOBILL = '1'.str_pad('0', 6, '0', STR_PAD_LEFT);
}
else {
if(strlen(substr($LASTNOBILL,2)) < 6) {
$xLASTNOBILL = str_pad( (substr($LASTNOBILL,2)+$p), 6, '0', STR_PAD_LEFT);
}
else {
$xLASTNOBILL = str_pad( (substr($LASTNOBILL,2)+$p), strlen(substr($LASTNOBILL,2)), '0', STR_PAD_LEFT);
}
}
$nomor = $PRE_NO.$xLASTNOBILL;
$this->nobill = ($nomor + 1);
}
else {
$this->nobill = $PRE_NO.'000001';
}
// $get_no = $db->query("SELECT nomor from m_maxnobill where type = 'bill_pasien'");
// $nomor = $get_no->fetchFirst()['nomor'];
// if($nomor == null)
// {
// $this->nobill = date('y').'000001';
// }
// else {
// $this->nobill = ($nomor + 1);
// }
execute("UPDATE m_maxnobill set nomor = ".$this->nobill." where type = 'bill_pasien' ");
}
}
}
public function setBatalBill($param) {
global $db;
$this->status_batal = TRUE;
$st_rajal = ($this->tempatlayanan == 'irja' || $this->tempatlayanan == 'nonregister') ? 1 : 0;
$where_idxbill = (is_array($param['idxbill_batal'])) ? " and a.idxbill in (".implode(",",$param['idxbill_batal']).")" : " and a.idxbill = ".$param['idxbill_batal'];
$currtime = date('Y-m-d H:i:s');
$save_m_batal = "INSERT INTO m_batal (kodetarif,nomr,tglbatal,shift,carabayar,nip,tarif,qty,keterangan,kdpoly,kddokter,idbayar,nonota,rajal)
SELECT a.kodetarif, a.nomr,'$currtime',a.shift,a.carabayar,'{$this->user}',tarifrs,qty,'{$param['alasan']}',kdpoly,kddokter,b.idxbayar,{$this->nonota},$st_rajal
FROM {$this->tbl_billing} a
JOIN {$this->tbl_bayarbilling} b ON a.idxbill = b.idxbill WHERE a.nobill = b.nobill ".$where_idxbill;
$sql_batal = execute($save_m_batal);
$where_idxbill2 = (is_array($param['idxbill_batal'])) ? "idxbill in (".implode(",",$param['idxbill_batal']).")" : "idxbill = ".$param['idxbill_batal'] ;
execute("UPDATE {$this->tbl_billing} set status = 'BATAL' where ".$where_idxbill2);
}
private function createBill() {
global $db;
$tgl_transaksi = date('Y-m-d H:i:s');
if($this->tempatlayanan == 'irna') {
$get_kode_ruang = $db->query("SELECT noruang from t_admission where id_admission = {$this->idxdaftar}");
$kode_ruang = $get_kode_ruang->fetchFirst()['noruang'];
}
elseif($this->tempatlayanan == 'irja') {
if($this->aps == 1) {
$kode_ruang = $this->poliklinik;
}
else {
$get_kode_ruang = $db->query("SELECT kdpoly from t_pendaftaran where idxdaftar = {$this->idxdaftar}");
$kode_ruang = $get_kode_ruang->fetchFirst()['kdpoly'];
}
}
elseif($this->tempatlayanan == 'nonregister') {
$get_kode_ruang = $db->query("SELECT ruang from m_nonreg where idx_nonreg = {$this->idxdaftar}");
$kode_ruang = $get_kode_ruang->fetchFirst()['ruang'];
}
$bill_ranap = ($this->tempatlayanan == 'irna') ? "{$this->unit},a.discount,0" : "{$this->unit}";
$build_query = "INSERT INTO ".$this->tbl_billing." (".implode(',',$this->col_bill[$this->tbl_billing]).") ";
if($this->status_batal) {
$build_query .= "SELECT a.kodetarif,'{$this->nomr}','{$this->tanggal}',{$this->shift},'{$this->user}',a.qty,{$this->idxdaftar},{$this->nobill},a.jasa_sarana,a.jasa_pelayanan,a.jasa_anastesi,a.tarif,{$this->poliklinik},{$this->carabayar},{$this->aps},a.kddokter,$bill_ranap,{$this->nonota},'BATAL' FROM tmp_cartbayar a WHERE a.ip = '{$this->ipaddress}'";
}
else {
if($this->tempatlayanan == 'nonregister') {
$build_query .= "SELECT a.kodetarif,'{$this->nomr}','{$this->tanggal}',{$this->shift},'{$this->user}',a.qty,{$this->idxdaftar},{$this->nobill},a.jasa_sarana,a.jasa_pelayanan,a.jasa_anastesi,a.tarif,{$this->carabayar},a.kddokter,$bill_ranap,{$this->nonota},{$this->poliklinik},'$tgl_transaksi' as tgl_transaksi,$kode_ruang as kode_ruang FROM tmp_cartbayar a WHERE a.ip = '{$this->ipaddress}'";
}
else {
$build_query .= "SELECT a.kodetarif,'{$this->nomr}','{$this->tanggal}',{$this->shift},'{$this->user}',a.qty,{$this->idxdaftar},{$this->nobill},a.jasa_sarana,a.jasa_pelayanan,a.jasa_anastesi,a.tarif,{$this->poliklinik},{$this->carabayar},{$this->aps},a.kddokter,$bill_ranap,{$this->nonota},'$tgl_transaksi' as tgl_transaksi,$kode_ruang as kode_ruang FROM tmp_cartbayar a WHERE a.ip = '{$this->ipaddress}' ORDER BY idxbayar";
}
}
if(_DBTYPE_ == 'mysqli') {
$insert_bill = execute($build_query);
$id_bill = $insert_bill->insertid;
}
else {
$insert_bill = execute($build_query.' RETURNING idxbill');
$id_bill = $insert_bill->fetchFirst()['idxbill'];
}
$tmp_cartbayar_detil = $db->query("SELECT * from tmp_cartbayar_detil where idxbayar in ( select idxbayar from tmp_cartbayar where ip = '{$this->ipaddress}') ORDER by idxbayar");
if($tmp_cartbayar_detil->numRows() > 0){
foreach($tmp_cartbayar_detil->fetchAll() as $row) {
$data_bill_detil = [
'id_bill'=>$id_bill,
'kddokter'=>$row['kddokter'],
'kode_tarif'=>$row['kode_tarif'],
'komponen'=>$row['komponen'],
'nilai'=>$row['nilai']
];
if($row['kddokter'] == '')
{
unset($data_bill_detil['kddokter']);
}
$insert_billdetil = "INSERT INTO ".$this->tbl_billingdetil." ".bind_sql($data_bill_detil);
execute($insert_billdetil);
}
}
return $insert_bill;
}
private function createBayar() {
global $db;
// if($this->carabayar > 1)
// {
// $tgl_bayar = date('Y-m-d');
// $jam_bayar = date('H:i:s');
// $user_bayar = $this->user;
// $shift_bayar = $this->shift;
// $tbp_bayar = 0;
// $lunas_bayar = 1;
// $status_bayar = 'LUNAS';
// }
// else {
$jml_bayar = ($this->tempatlayanan == 'irna') ? '0' : '(tarifrs*qty)';
$tgl_bayar = '0001-01-01';
$jam_bayar = '00:00:00';
$user_bayar = '';
$shift_bayar = '0';
$tbp_bayar = '0';
$lunas_bayar = '0';
$status_bayar = ($this->status_batal) ? 'BATAL' : 'TRX';
$field_bayar = ($this->tempatlayanan == 'irna') ? "(discount*qty) as discount,{$this->poliklinik},{$this->unit},'".date('Y-m-d')."'" : "{$this->unit}";
// }
if ($this->tempatlayanan == 'irna') {
$where = "where idxdaftar = $this->idxdaftar and nip = '$this->user' AND idxbill NOT IN ( SELECT idxbill FROM {$this->tbl_bayarbilling} WHERE idxdaftar = $this->idxdaftar and idxbill is not null)";
}
elseif ($this->tempatlayanan == 'irja') {
$where = "where nobill = $this->nobill and idxdaftar = $this->idxdaftar and nip = '$this->user' AND idxbill NOT IN ( SELECT idxbill FROM {$this->tbl_bayarbilling} WHERE nobill = $this->nobill and idxdaftar = $this->idxdaftar and idxbill is not null)";
}
elseif ($this->tempatlayanan == 'nonregister') {
$where = "where nobill = $this->nobill and idx_nonreg = $this->idxdaftar and nip = '$this->user' AND idxbill NOT IN ( SELECT idxbill FROM {$this->tbl_bayarbilling} WHERE nobill = $this->nobill and idx_nonreg = $this->idxdaftar and idxbill is not null)";
}
$build_query = "INSERT INTO {$this->tbl_bayarbilling} (".implode(',', $this->col_bill[$this->tbl_bayarbilling]).") ";
if($this->status_batal) {
$build_query .= "SELECT '{$this->nomr}',$shift_bayar,'$user_bayar',$this->idxdaftar,$this->nobill,(jasa_sarana*-1),(jasa_pelayanan*-1),(jasa_anastesi*-1),(tarifrs*-1),$this->carabayar,$this->aps,'$tgl_bayar','$jam_bayar',$jml_bayar,$tbp_bayar,$lunas_bayar,'$status_bayar',$field_bayar,idxbill FROM {$this->tbl_billing} ".$where;
}
else {
if ($this->tempatlayanan == 'nonregister') {
$build_query .= "SELECT '{$this->nomr}',$shift_bayar,'$user_bayar',$this->idxdaftar,$this->nobill,(jasa_sarana*qty),(jasa_pelayanan*qty),(jasa_anastesi*qty),(tarifrs*qty),$this->carabayar,'$tgl_bayar','$jam_bayar',$jml_bayar,$tbp_bayar,$lunas_bayar,'$status_bayar',$field_bayar,idxbill FROM {$this->tbl_billing} ".$where;
}
else {
$build_query .= "SELECT '{$this->nomr}',$shift_bayar,'$user_bayar',$this->idxdaftar,$this->nobill,(jasa_sarana*qty),(jasa_pelayanan*qty),(jasa_anastesi*qty),(tarifrs*qty),$this->carabayar,$this->aps,'$tgl_bayar','$jam_bayar',$jml_bayar,$tbp_bayar,$lunas_bayar,'$status_bayar',$field_bayar,idxbill FROM {$this->tbl_billing} ".$where." ORDER BY idxbill";
}
}
$insert_bayar = execute($build_query);
if($insert_bayar)
{
// delete temporary
$delete_temp = execute("DELETE FROM tmp_cartbayar_detil where idxbayar in (select idxbayar from tmp_cartbayar where ip = '$this->ipaddress')");
$delete_temp = execute("DELETE FROM tmp_cartbayar where ip = '$this->ipaddress'");
return $insert_bayar;
}
else {
return false;
}
}
}
+414
View File
@@ -0,0 +1,414 @@
<?php
/**
* BPJS Class
* Description : Class untuk akses REST API BPJS Vclaim, dengan menggunakan class ini
* user dimudahkan untuk melakukan operasi pada aplikasi vclaim BPJS.
*
* Require : GuzzleHTTP, Monolog
* BPJS Vclaim Version : 1.1
* Version : 1.0
* Author : nuril.isbah@gmail.com
* Parameter : mixed
* Return : Array
*
* How to use this class :
* - Create new object
* $bpjs = new BPJS([
* 'BPJS_CONSID'=>'CONSID',
* 'BPJS_KEY'=>'SECRETKEY',
* 'BPJS_VCLAIM_URL'=>'URL SERVICE',
* ]);
*
* - Define katalog and parameter
* $request = ['katalog'=>'peserta','parameter'=['nokartu','xx000123456','2019-01-01']];
*
* - Get result
* $result = $bpjs->request($request,(DEBUG=BOOLEAN,OBJECT_ONLY=BOOLEAN));
*
**/
use GuzzleHttp\Client;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\RequestException;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\FirePHPHandler;
Class BPJS {
private $consId;
private $secretkey;
private $serviceUrl;
private $header;
private $timeStamp;
private $requestURL;
private $contentType;
private $method;
public function __construct($cons_id,$secret_key,$service_url)
{
$this->consId = $cons_id;
$this->secretkey = $secret_key;
$this->serviceUrl = $service_url;
}
private function setHeader()
{
date_default_timezone_set('Asia/Jakarta');
$this->timeStamp = strval(strtotime('now'));
$signature = hash_hmac('sha256', $this->consId."&".$this->timeStamp, $this->secretkey, true);
$encodedSignature = base64_encode($signature);
$context = [
'headers' => [
'Accept' => 'application/json',
'Content-type' => $this->contentType,
'X-cons-id' => $this->consId,
'X-timestamp' => $this->timeStamp,
'X-signature' => $encodedSignature,
]
];
$this->header = $context['headers'];
}
private function setUrl($param)
{
if($param['katalog'] != null)
{
switch ($param['katalog']) {
case 'peserta':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/Peserta/'.$param['parameter'][0].'/'.$param['parameter'][1].'/tglSEP/'.$param['parameter'][2];
break;
}
// Referensi
case 'poli':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/referensi/poli/'.$param['parameter'][0];
break;
}
case 'faskes':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/referensi/faskes/'.$param['parameter'][0].'/'.$param['parameter'][1];
break;
}
case 'propinsi':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/referensi/propinsi';
break;
}
case 'kabupaten':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/referensi/kabupaten/propinsi/'.$param['parameter'][0];
break;
}
case 'kecamatan':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/referensi/kecamatan/kabupaten/'.$param['parameter'][0];
break;
}
case 'dpjp':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/referensi/dokter/pelayanan/'.$param['parameter'][0].'/tglPelayanan/'.$param['parameter'][1].'/Spesialis/'.$param['parameter'][2];
break;
}
case 'diagnosa':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/referensi/diagnosa/'.$param['parameter'][0];
break;
}
// SEP
case 'insert_sep':
{
$this->method = 'POST';
$this->contentType = 'application/x-www-form-urlencoded';
$this->requestURL = '/SEP/1.1/insert';
break;
}
case 'update_sep':
{
$this->method = 'PUT';
$this->contentType = 'application/x-www-form-urlencoded';
$this->requestURL = '/SEP/1.1/Update';
break;
}
case 'hapus_sep':
{
$this->method = 'DELETE';
$this->contentType = 'application/x-www-form-urlencoded';
$this->requestURL = '/SEP/Delete';
break;
}
case 'sep':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/SEP/'.$param['parameter'][0];
break;
}
case 'suplesi':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/sep/JasaRaharja/Suplesi/'.$param['parameter'][0].'/tglPelayanan/'.$param['parameter'][1];
break;
}
case 'update_pulang':
{
$this->method = 'PUT';
$this->contentType = 'application/x-www-form-urlencoded';
$this->requestURL = '/Sep/updtglplg';
break;
}
// RUJUKAN
case 'rujukan_pcare':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/Rujukan/'.$param['parameter'][0];
break;
}
case 'rujukan_RS':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/Rujukan/RS/'.$param['parameter'][0];
break;
}
case 'rujukan_pcare_kartu1':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/Rujukan/Peserta/'.$param['parameter'][0];
break;
}
case 'rujukan_RS_kartu1':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/Rujukan/RS/Peserta/'.$param['parameter'][0];
break;
}
case 'rujukan_pcare_kartumulti':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/Rujukan/List/Peserta/'.$param['parameter'][0];
break;
}
case 'rujukan_RS_kartumulti':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/Rujukan/RS/List/Peserta/'.$param['parameter'][0];
break;
}
case 'insert_rujukan':
{
$this->method = 'POST';
$this->contentType = 'Application/x-www-form-urlencoded';
$this->requestURL = '/Rujukan/insert';
break;
}
case 'update_rujukan':
{
$this->method = 'PUT';
$this->contentType = 'Application/x-www-form-urlencoded';
$this->requestURL = '/Rujukan/update';
break;
}
case 'delete_rujukan':
{
$this->method = 'DELETE';
$this->contentType = 'Application/x-www-form-urlencoded';
$this->requestURL = '/Rujukan/delete';
break;
}
// Referensi LPK
case 'tindakan':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/referensi/procedure/'.$param['parameter'][0];
break;
}
case 'kelasrawat':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/referensi/kelasrawat';
break;
}
case 'ruangrawat':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/referensi/ruangrawat';
break;
}
case 'dokter':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/referensi/dokter';
break;
}
case 'spesialistik':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/referensi/spesialistik';
break;
}
case 'carakeluar':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/referensi/carakeluar';
break;
}
case 'pascapulang':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/referensi/pascapulang';
break;
}
// LPK
case 'insert_lpk':
{
$this->method = 'GET';
$this->contentType = 'Application/x-www-form-urlencoded';
$this->requestURL = '/LPK/insert';
break;
}
case 'update_lpk':
{
$this->method = 'PUT';
$this->contentType = 'Application/x-www-form-urlencoded';
$this->requestURL = '/LPK/update';
break;
}
case 'delete_lpk':
{
$this->method = 'DELETE';
$this->contentType = 'Application/x-www-form-urlencoded';
$this->requestURL = '/LPK/delete';
break;
}
case 'list_lpk':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/LPK/TglMasuk/'.$param['parameter'][0].'/JnsPelayanan/'.$param['parameter'][1];
break;
}
case 'monitor_kunjungan':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/Monitoring/Kunjungan/Tanggal/'.$param['parameter'][0].'/JnsPelayanan/'.$param['parameter'][1];
break;
}
case 'monitor_klaim':
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = '/Monitoring/Klaim/Tanggal/'.$param['parameter'][0].'/JnsPelayanan/'.$param['parameter'][1].'/Status/'.$param['parameter'][2];
break;
}
// DEFAULT
default:
{
$this->method = 'GET';
$this->contentType = 'application/json; charset=utf-8';
$this->requestURL = null;
break;
}
}
}
}
public function request($args, $debug = FALSE, $object_only = FALSE)
{
if($this->consId == null || $this->secretkey == null) {
return false;
}
$this->setUrl($args);
$this->setHeader();
if($debug == TRUE)
{
$this->log($this->method."\r\n".$this->serviceUrl.$this->requestURL."\r\n".http_build_query($this->header));
}
$client = new GuzzleHttp\Client();
$url_request = $this->serviceUrl.$this->requestURL;
try {
$request = new Request($this->method, $url_request, $this->header, $args['body']);
$obj_request = $client->send($request);
$json_request = ($obj_request->getStatusCode() == 200) ? $obj_request->getBody()->getContents() : [];
if($object_only == TRUE) {
return $json_request;
}
else {
return (array) json_decode($json_request);
}
}
catch(RequestException $e){
return Psr7\str($e->getRequest());
if ($e->hasResponse()) {
return Psr7\str($e->getResponse());
}
}
}
private function log($string)
{
$logger = new Logger('BPJS');
$daily_log = date('d-m-Y').'.log';
$logger->pushHandler(new StreamHandler(_DOCROOT_.'logs/bpjs_logs/'.$daily_log, Logger::INFO));
$logger->pushHandler(new FirePHPHandler());
$logger->addInfo($string);
}
}
+699
View File
@@ -0,0 +1,699 @@
<?php
require_once 'db.php';
Class Eklaim {
var $rs_id;
var $user;
var $user_id;
var $db;
var $column_bill = ['procedure_amt','surgical_amt','consul_amt','expert_amt','nursing_amt','ancillary_amt','blood_amt','laboratory_amt','radiology_amt','rehab_amt','room_amt','intensive_amt','drug_amt','device_amt','consumable_amt','device_rent_amt','drug_chronic_amt','drug_chemo_amt'];
function __construct($host, $user, $password, $database) {
// u:itcc_casemix p:c4s3m1x
// u:root p:sQHvwl6k
if($host == '' || $user == '' || $password == '' || $database == '') {
return false;
}
else {
$this->db = new db('p:'.$host,$user,$password,$database);
}
return $this;
}
function setVar($param) {
if($param['user'] != ''){
$this->user = $param['user'];
}
if($param['rs_id'] != ''){
$this->rs_id = $param['rs_id'];
}
}
// referensi
function getBuild() {
if(!empty($this->user)) {
$result = $this->db->query("SELECT patch_number from xocp_patch order by patch_id desc limit 1");
return $result->fetchFirst();
}
return false;
}
function getPasien($patient_id) {
if(!empty($this->user)) {
$result = $this->db->query("SELECT person_id,person_nm,birth_dttm,patient_mrn,nokartu from xocp_his_patient a join xocp_persons b on a.person_id = b.person_id where a.patient_id = {$patient_id}");
return $result->fetchAll();
}
return false;
}
function getPayplan() {
if(!empty($this->user)) {
$result = $this->db->query("SELECT * from xocp_his_payplan");
return $result->fetchAll();
}
return false;
}
function getCOB() {
if(!empty($this->user)) {
$result = $this->db->query("SELECT * from xocp_his_cob");
return $result->fetchAll();
}
return false;
}
function getDPJP() {
if(!empty($this->user)) {
$result = $this->db->query("SELECT * from xocp_his_dpjp");
return $result->fetchAll();
}
return false;
}
function getDiagnosa($query) {
if(!empty($this->user)) {
$result = $this->db->query("SELECT code,str from mrconso where code like '$query%' OR str like '%$query%'");
return $result->fetchAll();
}
return false;
}
function getProsedur($query) {
if(!empty($this->user)) {
$result = $this->db->query("SELECT code,str from mrconso where code like '$query%' OR str like '%$query%'");
return $result->fetchAll();
}
return false;
}
function getKlaim($patient_id) {
if(!empty($this->user)) {
$result = $this->db->query("SELECT hospital_admission_id,admission_dttm,admission_type,discharge_dttm,payplan_nm,no_sep,cbg_code,user_nm,klaim_status_cd from xocp_his_patient_admission a
JOIN xocp_his_payplan b on a.payplan_id = b.payplan_id
JOIN xocp_users u on a.created_user_id = u.user_id
LEFT JOIN xocp_his_cbg_result c on a.patient_id = c.patient_id and a.admission_id = c.admission_id
where a.patient_id = {$patient_id} and a.status_cd = 'normal'
ORDER BY admission_dttm desc");
$user_data = $result->fetchAll();
return $user_data;
}
return false;
}
function editKlaim($patient_id,$hospital_admission_id) {
if(!empty($this->user)) {
$query['admission'] = $this->db->query("SELECT a.hospital_admission_id, a.patient_id, a.admission_id, a.admission_type, a.admission_dttm, a.org_id, a.rs_tariff, a.discharge, a.discharge_status, a.discharge_dttm, a.payplan_id, a.no_kartu, a.no_sep, a.attending_doctor_id, a.attending_doctor_nm, a.status_cd, a.tariff_class, a.outpatient_class, a.los, a.adl1, a.adl2, a.special_procedure, a.special_prosthesis, a.special_investigation, a.special_drugs, a.birth_weight, a.billing_amount, a.billing_amount_pex, a.icu_ind, a.icu_los, a.vent_hour, a.upgrade_class_ind, a.upgrade_class_class, a.upgrade_class_los, a.grouping_count, a.unugrouper_version, a.klaim_status_cd, a.migrated_patient_id, a.migrated_admission_id, a.grouper_dttm, a.grouper_user_id, a.severity, a.bpjs_status_cd, a.rs_no, a.add_payment_pct, a.add_payment_amt, a.cob_id, b.person_id, b.patient_mrn, b.nokartu, c.person_nm, c.birth_dttm, c.adm_gender_cd
FROM xocp_his_patient_admission a
JOIN xocp_his_patient b on a.patient_id = b.patient_id
JOIN xocp_persons c on b.person_id = c.person_id
where a.hospital_admission_id = {$hospital_admission_id}");
$user_data['admission'] = $query['admission']->fetchFirst();
$tgl_lahir_pasien = ($user_data['admission']['birth_dttm'] != null ||
$user_data['admission']['birth_dttm'] != '0000-00-00 00:00:00') ? new Datetime( datetime_to_date_en($user_data['admission']['birth_dttm']) ) : false;
$tgl_sekarang = new Datetime(date('Y-m-d'));
$differ_date = ($tgl_lahir_pasien != false) ? $tgl_lahir_pasien->diff($tgl_sekarang) : 0;
$user_data['admission']['umur'] = $differ_date->format("%Y tahun");
$admission_id = $user_data['admission']['admission_id'];
$tarif_class = preg_replace("/kelas\_/",'',$user_data['admission']['tariff_class']);
$upgrade_ind = $user_data['admission']['upgrade_class_ind'];
$tarif_upgrade = preg_replace("/kelas\_/",'',$user_data['admission']['upgrade_class_class']);
$query['billing'] = $this->db->query("SELECT ".implode(", ", $this->column_bill)."
FROM xocp_his_billing_detail
where hospital_admission_id = {$hospital_admission_id}");
if($query['billing']->numRows() > 0){
$user_data['billing'] = $query['billing']->fetchFirst();
}
else {
foreach($this->column_bill as $col) {
$user_data['billing'][$col] = 0;
}
}
$query['diag'] = $this->db->query("SELECT *
FROM xocp_his_patient_discharge_diag a
JOIN mrconso b on a.diag_cd = b.CODE
where a.patient_id = {$patient_id} and a.admission_id = {$admission_id}
ORDER BY diag_no");
$user_data['diag'] = $query['diag']->fetchAll();
$query['proc'] = $this->db->query("SELECT *
FROM xocp_his_patient_discharge_proc a
JOIN mrconso b on a.proc_cd = b.CODE
where a.patient_id = {$patient_id} and a.admission_id = {$admission_id}
ORDER BY proc_no");
$user_data['proc'] = $query['proc']->fetchAll();
$query['result'] = $this->db->query("SELECT *,(select code from ina_grouper4_specialgroups_20230124 s_sp where s_sp.Code_full = xocp_his_cbg_result.sp and s_sp.INACBG = xocp_his_cbg_result.cbg_code)as sp_code,(select code from ina_grouper4_specialgroups_20230124 s_sr where s_sr.Code_full = xocp_his_cbg_result.sr and s_sr.INACBG = xocp_his_cbg_result.cbg_code) as sr_code,(select code from ina_grouper4_specialgroups_20230124 s_si where s_si.Code_full = xocp_his_cbg_result.si and s_si.INACBG = xocp_his_cbg_result.cbg_code)as si_code,(select code from ina_grouper4_specialgroups_20230124 s_sd where s_sd.Code_full = xocp_his_cbg_result.sd and s_sd.INACBG = xocp_his_cbg_result.cbg_code)as sd_code
FROM xocp_his_cbg_result
JOIN unucbg_2016 on xocp_his_cbg_result.cbg_code = unucbg_2016.code
where patient_id = {$patient_id} and admission_id = {$admission_id}");
if($query['result']->numRows() > 0) {
$user_data['result'] = $query['result']->fetchFirst();
$cbg_code = $user_data['result']['cbg_code'];
// get rs setup
$rs = $this->db->query("SELECT rs_tariff, regional FROM rs_setup where rs_no = '".$this->rs_id."'");
$rs_data = $rs->fetchFirst();
if($cbg_code != '') {
$query['tariff'] = $this->db->query("SELECT * FROM tariff_20230124 WHERE tariff_20230124.INACBG = '{$cbg_code}' AND tariff_20230124.REGIONAL = '{$rs_data['regional']}' AND tariff_20230124.KODE_TARIFF = '{$rs_data['rs_tariff']}'");
// $query['tariff'] = $this->db->query("SELECT * FROM tariff WHERE tariff.INACBG = '{$cbg_code}' AND tariff.REGIONAL = '{$rs_data['regional']}' AND tariff.KODE_TARIFF = '{$rs_data['rs_tariff']}'");
$arr_tarif=[];
foreach($query['tariff']->fetchAll() as $row_tarif) {
$arr_tarif[$row_tarif['KELAS_RAWAT']] = $row_tarif['TARIFF'];
}
$user_data['tariff'][$tarif_class] = $arr_tarif[$tarif_class];
if($upgrade_ind == 1 && preg_match("/vip/", $tarif_upgrade)) {
$user_data['tariff'][$tarif_upgrade] = $arr_tarif[1];
}
else{
$user_data['tariff'][$tarif_upgrade] = $arr_tarif[$tarif_upgrade];
}
// get special cmg
$cmg_query = $this->db->query("SELECT a.*,b.TARIFF,case CMG_type when 'Special Procedure' then 'sp' when 'Special Prosthesis' then 'sr' when 'Special Investigation' then 'si' when 'Special Drug' then 'sd' end as cmg from ina_grouper4_specialgroups_20230124 a join special_cmg_tariff_20230124 b on a.Code_Full = b.CODE_FULL and a.INACBG = b.INACBG
where a.INACBG = '$cbg_code' and REGIONAL = 'reg1' and KODE_TARIFF = 'AP' ");
if($cmg_query->numRows() > 0) {
foreach($cmg_query->fetchAll() as $row){
$user_data['cmg'][$row['cmg']][$row['Code']] = $row['CMG_Description'];
}
}
}
}
return $user_data;
}
return false;
}
function getUserNik($user_id) {
if(!empty($this->user)) {
$result = $this->db->query("SELECT ext_id from xocp_persons p join xocp_users u on p.person_id = u.person_id where u.user_nm = '$user_id'");
$user_data = $result->fetchFirst();
return $user_data;
}
return false;
}
// end referensi
function setUserID() {
if(!empty($this->user)) {
$result = $this->db->query("SELECT * from xocp_users where user_nm = '".$this->user."'");
$user_data = $result->fetchFirst();
$this->user_id = $user_data['user_id'];
}
return false;
}
function getCounterKlaim($patient_id) {
if(!empty($this->user)) {
$result = $this->db->query("SELECT count(admission_id) as jml_admisi from xocp_his_patient_admission where patient_id = ".$patient_id." and status_cd = 'normal'");
$user_data = $result->fetchFirst();
return $user_data['jml_admisi'];
}
return false;
}
private function insert($table, $param) {
$column = $values = [];
$column = array_keys($param);
$values = array_values($param);
$this->db->debugging = TRUE;
$save = $this->db->query("INSERT INTO $table(".implode(",",$column).") VALUES ('".implode("','",$values)."')");
$this->db->debugging = FALSE;
return $save;
}
private function update($table, $data, $where) {
$str_value = 'SET ';
$arr_set = array();
foreach($data as $key => $value)
{
if(is_array($value)) {
$val = $value['value'];
$type = $value['type'];
if($type == 'number') {
$arr_set[] = $key." = ".$val;
}
}
else {
$arr_set[] = $key." ='".$value."'";
}
}
$str_value .= implode(",".PHP_EOL,$arr_set);
$this->db->debugging = TRUE;
$save = $this->db->query("UPDATE $table $str_value WHERE $where");
$this->db->debugging = FALSE;
return $save;
}
function insertPatient($param) {
if(!empty($this->user)) {
// get patient by patient_mrn first, if found return patient_id
$get_patient = $this->db->query("SELECT * from xocp_his_patient where patient_mrn = ".$param['norm']);
if($get_patient->numRows() > 0) {
return $get_patient->fetchFirst()['patient_id'];
}
else {
// insert into xocp_persons
$arr_persons = [
'person_nm' => $param['nama'],
'birth_dttm' => $param['tgl_lahir'],
'adm_gender_cd' => $param['jenis_kelamin'],
'created_user_id' => $this->user_id
];
$save_persons = $this->insert("xocp_persons",$arr_persons);
$id_person = $save_persons->insertid;
// insert into xocp_his_patient
$arr_patient = [
'person_id' => $id_person,
'patient_mrn' => $param['norm'],
'nokartu' => $param['nokartu'],
'created_user_id' => $this->user_id,
'rs_no' => $this->rs_id
];
$save_patient = $this->insert("xocp_his_patient",$arr_patient);
$id_patient = $save_patient->insertid;
return $id_patient;
}
}
return false;
}
function newClaim($param) {
if(!empty($this->user)) {
// get last admission id for this patient
$admisssion = $this->db->query("SELECT admission_id from xocp_his_patient_admission where patient_id = {$param['patient_id']} ORDER BY admission_id desc");
if($admisssion->numRows() > 0) {
$admission_id = $admisssion->fetchFirst()['admission_id']+1;
}
else {
$admission_id = 1;
}
// insert into xocp_his_patient_admission
$arr_admission = [
'patient_id' => $param['patient_id'],
'admission_id' => $admission_id,
'admission_dttm' => (($param['tgl_mrs'] != '') ? $param['tgl_mrs'] : date('Y-m-d H:i:s')),
'discharge' => 'home', // default home
'discharge_dttm' => (($param['tgl_krs'] != '') ? $param['tgl_krs'] : date('Y-m-d H:i:s')),
'payplan_id' => 3, // default JKN
'created_user_id' => $this->user_id,
'tariff_class' => 'kelas_3', // default kelas_3
'rs_no' => $this->rs_id,
'admission_type' => $param['admission_type']
];
$save_admission = $this->insert("xocp_his_patient_admission",$arr_admission);
$hospital_admission_id = $save_admission->insertid;
return $hospital_admission_id;
}
return false;
}
function updateKlaim($param, $result_grouper = [])
{
if(!empty($this->user)) {
// var_dump($param);
$param['diagnosa'] = $param['panelitem_1011_3'];
$param['procedure'] = $param['panelitem_1012_1'];
$admisssion = $this->db->query("SELECT admission_id from xocp_his_patient_admission where hospital_admission_id = {$param['hospital_admission_id']}");
if($admisssion->numRows() > 0) {
$admission_id = $admisssion->fetchFirst()['admission_id'];
}
list($attending_doctor_id,$attending_doctor_nm) = explode('|',$param['attending_doctor']);
// update billing detail
$get_billing = $this->db->query("SELECT * from xocp_his_billing_detail where hospital_admission_id = ".$param['hospital_admission_id']);
foreach($this->column_bill as $col) {
if(array_key_exists($col, $param)){
$arr_billing[$col] = $param[$col];
}
else {
$arr_billing[$col] = 0;
}
}
if($get_billing->numRows() > 0) {
// update billing
$this->update('xocp_his_billing_detail',$arr_billing,'hospital_admission_id='.$param['hospital_admission_id']);
}
else {
// insert billing
$arr_billing['hospital_admission_id'] = $param['hospital_admission_id'];
$this->insert('xocp_his_billing_detail',$arr_billing);
}
$bill_amount = array_sum(array_values($arr_billing));
// update xocp_his_patient_discharge_diag
$val_diag = explode("|", $param['diagnosa']);
$diag_no = 1;
$del_diag = $this->db->query("DELETE from xocp_his_patient_discharge_diag where patient_id = {$param['patient_id']} and admission_id = $admission_id");
foreach($val_diag as $diag_cd){
// insert diagnosa
$arr_diag['patient_id'] = $param['patient_id'];
$arr_diag['admission_id'] = $admission_id;
$arr_diag['diag_no'] = $diag_no;
$arr_diag['diag_cd'] = $diag_cd;
$this->insert('xocp_his_patient_discharge_diag',$arr_diag);
$diag_no++;
}
// update xocp_his_patient_discharge_proc
$val_proc = explode("|", $param['procedure']);
$proc_no = 1;
$del_proc = $this->db->query("DELETE from xocp_his_patient_discharge_proc where patient_id = {$param['patient_id']} and admission_id = {$admission_id}");
foreach($val_proc as $proc_cd){
// insert diagnosa
$arr_proc['patient_id'] = $param['patient_id'];
$arr_proc['admission_id'] = $admission_id;
$arr_proc['proc_no'] = $proc_no;
$arr_proc['proc_cd'] = $proc_cd;
$this->insert('xocp_his_patient_discharge_proc',$arr_proc);
$proc_no++;
}
// update his_cbg_result
// inisial value special group
$tariff_sp = $tariff_sr = $tariff_si = $tariff_sd = '0';
$vsp = $vsr = $vsi = $vsd = 'None';
$sp = $sr = $si = $sd = 'None';
$grouper_stage = (!empty($result_grouper)) ? 2 : 1;
$kelas_rawat = preg_replace("/kelas_/", '', $param['tariff_class']);
$st_result = true;
if(!array_key_exists(0, $val_diag)){
$st_result = false;
$cbg_code = 'X-0-98-X';
$cbg_tariff = 0;
}
else {
$cbg_code = $result_grouper['response']['cbg']['code'];
}
// get rs setup
$rs = $this->db->query("SELECT rs_tariff, regional FROM rs_setup where rs_no = '".$this->rs_id."'");
$rs_data = $rs->fetchFirst();
// tariff
$tariff = $this->db->query("SELECT TARIFF from tariff_20230124 where INACBG = '$cbg_code' and REGIONAL = '{$rs_data['regional']}' and KODE_TARIFF = '{$rs_data['rs_tariff']}' and KELAS_RAWAT = '$kelas_rawat'");
$cbg_tariff = ($tariff->numRows() > 0) ? $tariff->fetchFirst()['TARIFF'] : 0;
// patch
$get_patch = $this->db->query("SELECT patch_number from xocp_patch order by patch_id desc limit 1");
$patch_number = $get_patch->fetchFirst()['patch_number'];
$admission_dttm = str_replace("-","/",datetime_to_dateid($param['admission_dttm']));
$discharge_dttm = str_replace("-","/",datetime_to_dateid($param['discharge_dttm']));
$birth_dttm = str_replace("-","/",datetime_to_dateid($param['birth_dttm']));
$diagnosa = str_replace("|", ";", $param['diagnosa']);
$procedure = str_replace("|", ";", $param['procedure']);
/*
if(!empty($result_grouper)){
// var_dump($result_grouper);
$resp = $result_grouper['response'];
if(!empty($resp['special_cmg']))
{
foreach($resp['special_cmg'] as $special_cmg)
{
$query_cmg = "SELECT a.code,b.code_full,b.tariff,a.CMG_type from ina_grouper4_specialgroups_20230124 a JOIN special_cmg_tariff_20230124 b on a.code = b.CODE where a.INACBG = '$cbg_code' and b.INACBG = '$cbg_code' and b.REGIONAL = '{$rs_data['regional']}' and b.KODE_TARIFF = '{$rs_data['rs_tariff']}' and b.code_full = '{$special_cmg['code']}'";
$get_cmg = $this->db->query($query_cmg);
if($get_cmg->numRows() > 0) {
foreach($get_cmg->fetchAll() as $cmg){
if($cmg['CMG_Type'] == 'Special Procedure') {
$sp = $cmg['code_full'];
$vsp = $cmg['code'];
$tariff_sp = $cmg['tariff'];
}
elseif($cmg['CMG_Type'] == 'Special Prosthesis') {
$sr = $cmg['code_full'];
$vsr = $cmg['code'];
$tariff_sr = $cmg['tariff'];
}
elseif($cmg['CMG_Type'] == 'Special Investigation') {
$si = $cmg['code_full'];
$vsi = $cmg['code'];
$tariff_si = $cmg['tariff'];
}
elseif($cmg['CMG_Type'] == 'Special Drug') {
$sd = $cmg['code_full'];
$vsd = $cmg['code'];
$tariff_sd = $cmg['tariff'];
}
}
}
}
}
}
*/
if(array_key_exists('sp',$param) && $param['sp'] != '')
{
$query_cmg = "SELECT a.code,b.code_full,b.tariff,a.CMG_type from ina_grouper4_specialgroups_20230124 a JOIN special_cmg_tariff_20230124 b on a.code = b.CODE where a.INACBG = '$cbg_code' and b.INACBG = '$cbg_code' and b.REGIONAL = '{$rs_data['regional']}' and b.KODE_TARIFF = '{$rs_data['rs_tariff']}' and b.code = '{$param['sp']}' and a.CMG_Type = 'Special Procedure'";
// log_message('error',$query_cmg);
$get_cmg = $this->db->query($query_cmg);
if($get_cmg->numRows() > 0) {
$cmg = $get_cmg->fetchFirst();
$sp = $cmg['code_full'];
$vsp = $cmg['code'];
$tariff_sp = $cmg['tariff'];
}
}
if(array_key_exists('sr',$param) && $param['sr'] != '')
{
$query_cmg = "SELECT a.code,b.code_full,b.tariff,a.CMG_type from ina_grouper4_specialgroups_20230124 a JOIN special_cmg_tariff_20230124 b on a.code = b.CODE where a.INACBG = '$cbg_code' and b.INACBG = '$cbg_code' and b.REGIONAL = '{$rs_data['regional']}' and b.KODE_TARIFF = '{$rs_data['rs_tariff']}' and b.code = '{$param['sr']}' and a.CMG_Type = 'Special Prosthesis'";
// log_message('error',$query_cmg);
$get_cmg = $this->db->query($query_cmg);
if($get_cmg->numRows() > 0) {
$cmg = $get_cmg->fetchFirst();
$sr = $cmg['code_full'];
$vsr = $cmg['code'];
$tariff_sr = $cmg['tariff'];
}
}
if(array_key_exists('si',$param) && $param['si'] != '')
{
$query_cmg = "SELECT a.code,b.code_full,b.tariff,a.CMG_type from ina_grouper4_specialgroups_20230124 a JOIN special_cmg_tariff_20230124 b on a.code = b.CODE where a.INACBG = '$cbg_code' and b.INACBG = '$cbg_code' and b.REGIONAL = '{$rs_data['regional']}' and b.KODE_TARIFF = '{$rs_data['rs_tariff']}' and b.code = '{$param['si']}' and a.CMG_Type = 'Special Investigation'";
// log_message('error',$query_cmg);
$get_cmg = $this->db->query($query_cmg);
if($get_cmg->numRows() > 0) {
$cmg = $get_cmg->fetchFirst();
$si = $cmg['code_full'];
$vsi = $cmg['code'];
$tariff_si = $cmg['tariff'];
}
}
if(array_key_exists('sd',$param) && $param['sd'])
{
$query_cmg = "SELECT a.code,b.code_full,b.tariff,a.CMG_type from ina_grouper4_specialgroups_20230124 a JOIN special_cmg_tariff_20230124 b on a.code = b.CODE where a.INACBG = '$cbg_code' and b.INACBG = '$cbg_code' and b.REGIONAL = '{$rs_data['regional']}' and b.KODE_TARIFF = '{$rs_data['rs_tariff']}' and b.code = '{$param['sd']}' and a.CMG_Type = 'Special Drug'";
// log_message('error',$query_cmg);
$get_cmg = $this->db->query($query_cmg);
if($get_cmg->numRows() > 0) {
$cmg = $get_cmg->fetchFirst();
$sd = $cmg['code_full'];
$vsd = $cmg['code'];
$tariff_sd = $cmg['tariff'];
}
}
$arr_input_data = [1,$admission_dttm,$discharge_dttm,$birth_dttm,$param['birth_weight'],$grouper_stage,1,$diagnosa,$procedure,'-','-',$vsp,$vsr,$vsi,$vsd];
$total_tariff = $cbg_tariff + $tariff_sp + $tariff_sr + $tariff_si + $tarif_sd;
$arr_response_data = [$cbg_code,'None','None',$sp,$sr,$si,$sd];
$arr_result = [
'patient_id' => $param['patient_id'],
'admission_id' => $admission_id,
'patient_type' => 1,
'patient_class' => $kelas_rawat,
'input_data' => implode(' ', $arr_input_data),
'response_data' => implode(';', $arr_response_data),
'cbg_code' => $cbg_code,
'cbg_tariff' => $cbg_tariff,
'sub_acute' => 'None',
'tariff_sub_acute' => '0',
'chronic' => 'None',
'tariff_chronic' => '0',
'tariff_sac' => '0',
'sp' => $sp,
'tariff_sp' => $tariff_sp,
'sr' => $sr,
'tariff_sr' => $tariff_sr,
'si' => $si,
'tariff_si' => $tariff_si,
'sd' => $sd,
'tariff_sd' => $tariff_sd,
'rs_class' => 'A',
'rs_tariff' => 'AP',
'total_tariff' => $total_tariff,
'grouper_dttm' => date('Y-m-d H:i:s'),
'grouper_user_id' => $this->user_id,
'patch_number' => $patch_number
];
$get_result = $this->db->query("SELECT * from xocp_his_cbg_result where patient_id = {$param['patient_id']} and admission_id = $admission_id");
// var_dump($arr_result);
if($get_result->numRows() > 0) {
// update result
$this->update('xocp_his_cbg_result',$arr_result,'patient_id='.$param['patient_id'].' and admission_id='.$admission_id);
}
else {
// insert result
// $this->insert('xocp_his_cbg_result',$arr_result);
}
// End xocp_his_cbg_result
$tgl_admisi = new Datetime($param['admission_dttm']);
$tgl_keluar = new Datetime($param['discharge_dttm']);
$lama_rawat = ($tgl_keluar->diff($tgl_admisi)->format('%d')+1);
$arr_admission = [
'admission_type' => $param['admission_type'],
'payplan_id' => $param['payplan_id'],
'admission_dttm' => $param['admission_dttm'],
'discharge_dttm' => $param['discharge_dttm'],
'rs_tariff' => $param['rs_tariff'],
'discharge_status' => 1,
'no_kartu' => $param['no_kartu'],
'no_sep' => $param['no_sep'],
'attending_doctor_id' => $attending_doctor_id,
'attending_doctor_nm' => $attending_doctor_nm,
'tariff_class' => $param['tariff_class'],
'los' => $lama_rawat,
'adl1' => $param['adl1'],
'adl2' => $param['adl2'],
'adl2' => $param['adl2'],
'special_procedure' => (array_key_exists('sp',$param) && $param['sp'] != '') ? $param['sp'] : 'None' ,
'special_prosthesis' => (array_key_exists('sr',$param) && $param['sr'] != '') ? $param['sr'] : 'None',
'special_investigation' => (array_key_exists('si',$param) && $param['si'] != '') ? $param['si'] : 'None' ,
'special_drugs' => (array_key_exists('sd',$param) && $param['sd'] != '') ? $param['sd'] : 'None' ,
'birth_weight' => $param['birth_weight'],
'billing_amount' => $bill_amount,
'icu_ind' => $param['icu_ind'],
'icu_los' => $param['icu_los'],
'vent_hour' => $param['vent_hour'],
'upgrade_class_ind' => $param['upgrade_class_ind'],
'upgrade_class_class' => $param['upgrade_class_class'],
'upgrade_class_los' => $param['upgrade_class_los'],
'add_payment_pct' => $param['add_payment_pct'],
'add_payment_amt' => $param['add_payment_amt'],
// 'grouper_dttm' => date('Y-m-d H:i:s'),
'grouper_user_id' => $this->user_id,
];
$update_admission = $this->update('xocp_his_patient_admission',$arr_admission,'hospital_admission_id='.$param['hospital_admission_id']);
if($st_result){
return $cbg_code;
}
else {
return 'Invalid Parameters';
}
}
return false;
}
function insertBilling($param)
{
$arr_billingdetil = [
'hospital_admission_id' => $param['hospital_admission_id'],
'procedure_amt' => (array_key_exists('procedure_amt', $param) ? $param['procedure_amt'] : 0),
'surgical_amt' => (array_key_exists('surgical_amt', $param) ? $param['surgical_amt'] : 0),
'consul_amt' => (array_key_exists('consul_amt', $param) ? $param['consul_amt'] : 0),
'expert_amt' => (array_key_exists('expert_amt', $param) ? $param['expert_amt'] : 0),
'nursing_amt' => (array_key_exists('nursing_amt', $param) ? $param['nursing_amt'] : 0),
'ancillary_amt' => (array_key_exists('ancillary_amt', $param) ? $param['ancillary_amt'] : 0),
'blood_amt' => (array_key_exists('blood_amt', $param) ? $param['blood_amt'] : 0),
'laboratory_amt' => (array_key_exists('laboratory_amt', $param) ? $param['laboratory_amt'] : 0),
'radiology_amt' => (array_key_exists('radiology_amt', $param) ? $param['radiology_amt'] : 0),
'rehab_amt' => (array_key_exists('rehab_amt', $param) ? $param['rehab_amt'] : 0),
'room_amt' => (array_key_exists('room_amt', $param) ? $param['room_amt'] : 0),
'intensive_amt' => (array_key_exists('intensive_amt', $param) ? $param['intensive_amt'] : 0),
'drug_amt' => (array_key_exists('drug_amt', $param) ? $param['drug_amt'] : 0),
'device_amt' => (array_key_exists('device_amt', $param) ? $param['device_amt'] : 0),
'consumable_amt' => (array_key_exists('consumable_amt', $param) ? $param['consumable_amt'] : 0),
'device_rent_amt' => (array_key_exists('device_rent_amt', $param) ? $param['device_rent_amt'] : 0),
// 'consumable_capd_amt' => (array_key_exists('consumable_capd_amt', $param) ? $param['consumable_capd_amt'] : 0),
// 'transfer_set_amt' => (array_key_exists('transfer_set_amt', $param) ? $param['transfer_set_amt'] : 0),
// 'chronic_drug_amt' => (array_key_exists('chronic_drug_amt', $param) ? $param['chronic_drug_amt'] : 0),
// 'pet_scan_amt' => (array_key_exists('pet_scan_amt', $param) ? $param['pet_scan_amt'] : 0),
// 'chemo_drug_amt' => (array_key_exists('chemo_drug_amt', $param) ? $param['chemo_drug_amt'] : 0),
// 'eyeglass_amt' => (array_key_exists('eyeglass_amt', $param) ? $param['eyeglass_amt'] : 0),
// 'hearing_aid_amt' => (array_key_exists('hearing_aid_amt', $param) ? $param['hearing_aid_amt'] : 0),
// 'prosthetic_arm_amt' => (array_key_exists('prosthetic_arm_amt', $param) ? $param['prosthetic_arm_amt'] : 0),
// 'prosthetic_leg_amt' => (array_key_exists('prosthetic_leg_amt', $param) ? $param['prosthetic_leg_amt'] : 0),
// 'prosthetic_teeth_amt' => (array_key_exists('prosthetic_teeth_amt', $param) ? $param['prosthetic_teeth_amt'] : 0),
// 'corset_spine_amt' => (array_key_exists('corset_spine_amt', $param) ? $param['corset_spine_amt'] : 0),
// 'collar_neck_amt' => (array_key_exists('collar_neck_amt', $param) ? $param['collar_neck_amt'] : 0),
// 'walker_amt' => (array_key_exists('walker_amt', $param) ? $param['walker_amt'] : 0),
'drug_chronic_amt' => (array_key_exists('drug_chronic_amt', $param) ? $param['drug_chronic_amt'] : 0),
'drug_chemo_amt' => (array_key_exists('drug_chemo_amt', $param) ? $param['drug_chemo_amt'] : 0)
];
$save_billing = $this->insert('xocp_his_billing_detail',$arr_billingdetil);
}
function getAdmission($id) {
if($id != '') {
$result = $this->db->query("SELECT * from xocp_his_patient_admission where hospital_admission_id = ".$id);
}
return $result->fetchAll();
}
function hapusKlaim($id) {
if(!empty($this->user)) {
// update xocp_his_patient_admission
$arr_admission = [
'status_cd' => 'nullified',
'nullified_dttm' => date('Y-m-d H:i:s'),
'nullified_user_id' => $this->user_id
];
$hapus_admission = $this->update("xocp_his_patient_admission",$arr_admission,'hospital_admission_id='.$id);
return $hapus_admission;
}
return false;
}
}
?>
File diff suppressed because it is too large Load Diff
+432
View File
@@ -0,0 +1,432 @@
<?php
/**
* INCBG Class
* Description : Class untuk akses REST API INACBG E-Klaim, dengan menggunakan class ini
* user dimudahkan untuk melakukan operasi pada aplikasi E-Klaim.
*
* Require : GuzzleHTTP, Monolog
* INCBG E-Klaim Version : 5.3.8.201904220235
* Version : 1.0
* Author : nuril.isbah@gmail.com
*
* How to use this class :
* - Create new object
* $inacbg = new INACBG([
* 'INACBG_KEY'=>'SECRETKEY',
* 'INACBG_URL'=>'URL SERVICE',
* ]);
*
* - Get result
* $result = $inacbg->request($request);
*
**/
use GuzzleHttp\Client;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\RequestException;
Class INACBG {
private $secretkey;
private $serviceUrl;
private $method;
public $formated_data;
public function __construct($key, $url)
{
$this->secretkey = $key;
$this->serviceUrl = $url;
}
private function encrypt($data, $key)
{
$key = hex2bin($key);
if(mb_strlen($key,'8bit') !== 32)
{
throw new Exception("Error Processing Request. Need a 256 bit key");
}
// $iv_size = openssl_chiper_iv_length("aes-256-cbc");
$iv_size = 16;
$iv = random_bytes($iv_size);
$encrypted = openssl_encrypt($data, "aes-256-cbc", $key, OPENSSL_RAW_DATA, $iv);
$signature = mb_substr(hash_hmac("sha256", $encrypted, $key, true), 0, 10, '8bit');
$encoded = chunk_split(base64_encode($signature.$iv.$encrypted));
return $encoded;
}
private function decrypt($str, $key)
{
$key = hex2bin($key);
if(mb_strlen($key,'8bit') !== 32)
{
throw new Exception("Error Processing Request. Need a 256 bit key");
}
// $iv_size = openssl_chiper_iv_length("aes-256-cbc");
$iv_size = 16;
$decoded = base64_decode($str);
$signature = mb_substr($decoded, 0, 10, '8bit');
$iv = mb_substr($decoded,10,$iv_size,'8bit');
$encrypted = mb_substr($decoded,$iv_size+10,NULL,'8bit');
$calc_signature = mb_substr(hash_hmac("sha256", $encrypted, $key, true), 0, 10, '8bit');
if(!$this->compare($signature,$calc_signature))
{
return 'SIGNATURE_NOT_MATCH';
}
$decrypted = openssl_decrypt($encrypted, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
return $decrypted;
}
private function compare($signa1, $signa2)
{
if(strlen($signa1) !== strlen($signa2))
{
return false;
}
$result = 0;
for($i = 0; $i < strlen($signa1); $i++)
{
$result |= ord($signa1[$i]) ^ ord($signa2[$i]);
}
return $result == 0;
}
public function setMethod($method, $param)
{
$meta['metadata']['method'] = $method;
if($method == 'new_claim')
{
$cek_param = $this->validParam($param, ['nomor_kartu','nomor_sep','nomor_rm','nama_pasien','tgl_lahir','gender']);
if($cek_param == true) {
$format = array_merge(
$meta,
['data' => [
'nomor_kartu' => $param['nomor_kartu'],
'nomor_sep' => $param['nomor_sep'],
'nomor_rm' => $param['nomor_rm'],
'nama_pasien' => $param['nama_pasien'],
'tgl_lahir' => $param['tgl_lahir'],
'gender' => $param['gender']
]]);
}
}
elseif($method == 'update_patient')
{
$cek_param = $this->validParam($param, ['nomor_kartu','nomor_rm','nama_pasien','tgl_lahir','gender']);
if($cek_param == true) {
$meta['metadata']['nomor_rm'] = $param['nomor_rm'];
$format = array_merge(
$meta,
['data'=> [
'nomor_kartu' => $param['nomor_kartu'],
'nomor_rm' => $param['nomor_rm'],
'nama_pasien' => $param['nama_pasien'],
'tgl_lahir' => $param['tgl_lahir'],
'gender' => $param['gender']
]]);
}
}
elseif($method == 'delete_patient')
{
$cek_param = $this->validParam($param, ['nomor_rm','coder_nik']);
if($cek_param == true) {
$format = array_merge(
$meta,
['data' => [
'nomor_rm' => $param['nomor_rm'],
'coder_nik' => $param['coder_nik']
]]);
}
}
elseif($method == 'set_claim_data')
{
$cek_param = $this->validParam($param, ['nomor_sep','nomor_kartu','tgl_masuk','tgl_pulang',
'jenis_rawat','kelas_rawat','adl_sub_acute','adl_chronic','icu_indikator','icu_los','ventilator_hour','upgrade_class_ind','upgrade_class_class','upgrade_class_los','add_payment_pct','birth_weight','discharge_status','diagnosa','procedure','prosedur_non_bedah','prosedur_bedah','konsultasi','tenaga_ahli','keperawatan','penunjang','radiologi','laboratorium','pelayanan_darah','rehabilitasi','kamar','rawat_intensif','obat','obat_kronis','obat_kemoterapi','alkes','bmhp','sewa_alat','tarif_poli_eks','nama_dokter','kode_tarif','payor_id','payor_cd','cob_cd','coder_nik']);
if($cek_param == true) {
$format = array_merge(
$meta,
['data' => [
'nomor_sep' => $param['nomor_sep'],
'nomor_kartu' => $param['nomor_kartu'],
'tgl_masuk' => $param['tgl_masuk'],
'tgl_pulang' => $param['tgl_pulang'],
'jenis_rawat' => $param['jenis_rawat'],
'kelas_rawat' => $param['kelas_rawat'],
'adl_sub_acute' => $param['adl_sub_acute'],
'adl_chronic' => $param['adl_chronic'],
'icu_indikator' => $param['icu_indikator'],
'icu_los' => $param['icu_los'],
'ventilator_hour' => $param['ventilator_hour'],
'upgrade_class_ind' => $param['upgrade_class_ind'],
'upgrade_class_class' => $param['upgrade_class_class'],
'upgrade_class_los' => $param['upgrade_class_los'],
'add_payment_pct' => $param['add_payment_pct'],
'birth_weight' => $param['birth_weight'],
'discharge_status' => $param['discharge_status'],
'diagnosa' => $param['diagnosa'],
'procedure' => $param['procedure'],
'tarif_rs' => [
'prosedur_non_bedah' => $param['prosedur_non_bedah'],
'prosedur_bedah' => $param['prosedur_bedah'],
'konsultasi' => $param['konsultasi'],
'tenaga_ahli' => $param['tenaga_ahli'],
'keperawatan' => $param['keperawatan'],
'radiologi' => $param['radiologi'],
'laboratorium' => $param['laboratorium'],
'pelayanan_darah' => $param['pelayanan_darah'],
'rehabilitasi' => $param['rehabilitasi'],
'kamar' => $param['kamar'],
'rawat_intensif' => $param['rawat_intensif'],
'obat' => $param['obat'],
'obat_kronis' => $param['obat_kronis'],
'obat_kemoterapi' => $param['obat_kemoterapi'],
'alkes' => $param['alkes'],
'bmhp' => $param['bmhp'],
'sewa_alat' => $param['sewa_alat']
],
'tarif_poli_eks' => $param['tarif_poli_eks'],
'nama_dokter' => $param['nama_dokter'],
'kode_tarif' => $param['kode_tarif'],
'payor_id' => $param['payor_id'],
'payor_cd' => $param['payor_cd'],
'cob_cd' => $param['cob_cd'],
'coder_nik' => $param['coder_nik']
]]);
}
}
elseif($method == 'update_procedur')
{
$cek_param = $this->validParam($param, ['nomor_sep','procedure','coder_nik']);
if($cek_param == true) {
$meta['metadata']['method'] = 'set_claim_data';
$meta['metadata']['nomor_sep'] = $param['nomor_sep'];
$format = array_merge(
$meta,
['data' => [
'procedure' => $param['procedure'],
'coder_nik' => $param['coder_nik']
]]);
}
}
elseif($method == 'grouper_1')
{
$cek_param = $this->validParam($param, ['nomor_sep']);
if($cek_param == true) {
$meta['metadata']['method'] = 'grouper';
$meta['metadata']['stage'] = 1;
$format = array_merge(
$meta,
['data' => [
'nomor_sep' => $param['nomor_sep']
]]);
}
}
elseif($method == 'grouper_2')
{
$cek_param = $this->validParam($param, ['nomor_sep','special_cmg']);
if($cek_param == true) {
$meta['metadata']['method'] = 'grouper';
$meta['metadata']['stage'] = 2;
$format = array_merge($meta,
['data' => [
'nomor_sep' => $param['nomor_sep'],
'special_cmg' => $param['special_cmg']
]]);
}
}
elseif($method == 'claim_final')
{
$cek_param = $this->validParam($param, ['nomor_sep','coder_nik']);
if($cek_param == true) {
$format = array_merge(
$meta,
['data' => [
'nomor_sep' => $param['nomor_sep'],
'coder_nik' => $param['coder_nik']
]]);
}
}
elseif($method == 'reedit_claim')
{
$cek_param = $this->validParam($param, ['nomor_sep']);
if($cek_param == true) {
$format = array_merge(
$meta,
['data' => [
'nomor_sep' => $param['nomor_sep']
]]);
}
}
elseif($method == 'send_claim')
{
$cek_param = $this->validParam($param, ['start_dt','stop_dt','jenis_rawat','date_type']);
if($cek_param == true) {
$format = array_merge(
$meta,
['data' => [
'start_dt' => $param['start_dt'],
'stop_dt' => $param['stop_dt'],
'jenis_rawat' => $param['jenis_rawat'],
'date_type' => $param['date_type']
]]);
}
}
elseif($method == 'send_claim_individual')
{
$cek_param = $this->validParam($param, ['nomor_sep']);
if($cek_param == true) {
$format = array_merge(
$meta,
['data' => [
'nomor_sep' => $param['nomor_sep']
]]);
}
}
elseif($method == 'get_claim_data')
{
$cek_param = $this->validParam($param, ['nomor_sep']);
if($cek_param == true) {
$format = array_merge(
$meta,
['data' => [
'nomor_sep' => $param['nomor_sep']
]]);
}
}
elseif($method == 'get_claim_status')
{
$cek_param = $this->validParam($param, ['nomor_sep']);
if($cek_param == true) {
$format = array_merge(
$meta,
['data' => [
'nomor_sep' => $param['nomor_sep']
]]);
}
}
elseif($method == 'delete_claim')
{
$cek_param = $this->validParam($param, ['nomor_sep','coder_nik']);
if($cek_param == true) {
$format = array_merge(
$meta,
['data' => [
'nomor_sep' => $param['nomor_sep'],
'coder_nik' => $param['coder_nik']
]]);
}
}
elseif($method == 'claim_print')
{
$cek_param = $this->validParam($param, ['nomor_sep','coder_nik']);
if($cek_param == true) {
$format = array_merge(
$meta,
['data' => [
'nomor_sep' => $param['nomor_sep'],
'coder_nik' => $param['coder_nik']
]]);
}
}
elseif($method == 'sitb_validate')
{
$cek_param = $this->validParam($param, ['nomor_sep','nomor_register_sitb']);
if($cek_param == true) {
$format = array_merge(
$meta,
['data' => [
'nomor_sep' => $param['nomor_sep'],
'nomor_register_sitb' => $param['coder_nik']
]]);
}
}
$this->formated_data = json_encode($format);
}
private function validParam($param,$arr_key)
{
foreach($arr_key as $key)
{
if(!array_key_exists($key, $param))
{
return "Parameter ".$key." not found";
break;
}
else {
if($param[$key] == '')
{
return "Invalid Parameter on ".$key;
break;
}
}
}
return true;
}
public function request()
{
if($this->formated_data == '') { return false; }
$context = [
'headers' => [
'Accept' => 'application/json',
'Content-type' => 'application/x-www-form-urlencoded'
]
];
$ws_query = $this->encrypt($this->formated_data, $this->secretkey);
$client = new GuzzleHttp\Client();
try {
$request = new Request('POST', $this->serviceUrl, $context, $ws_query);
$obj_request = $client->send($request);
$json_request = ($obj_request->getStatusCode() == 200) ? $obj_request->getBody()->getContents() : [];
$first = strpos($json_request, "\n")+1;
$last = strrpos($json_request, "\n")-1;
$response = substr($json_request, $first, strlen($json_request)-$first-$last);
$response = $this->decrypt($response, $this->secretkey);
return json_decode($response, true);
}
catch(RequestException $e){
return Psr7\str($e->getRequest());
if ($e->hasResponse()) {
return Psr7\str($e->getResponse());
}
}
}
}
+67
View File
@@ -0,0 +1,67 @@
<?php
require_once '../core/LogReader/Exception.php';
abstract class LogReader_Abstract {
/**
*
* @var SplFileObject
*/
protected $_file;
/**
*
* @var string
*/
protected $_filename;
/**
*
* @var LogReader_Storage_Interface
*/
protected $_storage;
public function __construct($filename = '', $storage = null) {
if ($filename) {
$this->setFile($filename);
}
if ($storage) {
$this->setStorage($storage);
}
}
public function setFile($filename) {
$this->_filename = $filename;
if (!is_file($filename)) {
throw new LogReader_Exception("File '$filename' does not exist");
}
if (!is_readable($filename)) {
throw new LogReader_Exception("File '$filename' is not readable");
}
$this->_file = new SplFileObject($filename);
}
public function setStorage(LogReader_Storage_Interface $storage) {
$this->_storage = $storage;
}
abstract public function read();
/**
*
* @return LogReader_Storage_Interface
*/
public function getStorage() {
return $this->_storage;
}
/**
*
* @return string
*/
public function getFilename() {
return $this->_filename;
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
require_once 'LogReader/Abstract.php';
require_once 'LogReader/Item/ApachePhp.php';
class LogReader_ApachePhp extends LogReader_Abstract {
public function read() {
$item = new LogReader_Item_ApachePhp();
while (!$this->_file->eof()) {
if (preg_match('/^\[(?<date>.+?)\] \[(?:.+?)\] \[client (?<client>.+?)\] (?<php_type>PHP)?(?<message>.+?)(, referer: (?<referer>.+))?$/', $this->_file->fgets(), $matches)) {
$date = $matches['date'];
$message = $matches['message'];
if (preg_match('/^(Stack trace|[\d])/', trim($message))) {
//this line is part of stack trace
$item->appendStackTrace($message);
} else {
$this->_save($item);
$item = new LogReader_Item_ApachePhp();
$timestamp = date('Y-m-d H:i:s', strtotime($date));
$item->setTimestamp($timestamp);
if (!empty($matches['php_type'])) {
$type = $this->_getType($message);
} else {
$type = 'Apache';
}
$item->setType($type);
if (isset($matches['referer'])) {
$item->setReferer($matches['referer']);
}
if (isset($matches['client'])) {
$item->setClientIp($matches['client']);
}
$item->setMessage($message);
}
}
}
$this->_save($item);
}
protected function _getType($message) {
if (preg_match('/^([a-zA-Z0-9 ]+): /', $message, $matches) && isset($matches[1])) {
return trim($matches[1]);
}
}
protected function _save(LogReader_Item_ApachePhp $item) {
if ($item->getMessage() && $this->_storage) {
$stackTrace = $item->getStackTrace();
$messagesArray = array_merge(array($item->getMessage()), $stackTrace);
$item->setMessage(implode("\n", $messagesArray));
$this->_storage->save($item);
}
}
}
+3
View File
@@ -0,0 +1,3 @@
<?php
class LogReader_Exception extends Exception {}
+79
View File
@@ -0,0 +1,79 @@
<?php
abstract class LogReader_Item_Abstract {
/**
*
* @var string
*/
protected $_timestamp;
/**
*
* @var string
*/
protected $_type;
/**
*
* @var string
*/
protected $_message;
/**
*
* @var boolean
*/
protected $_isNew;
/**
* Unique id to distinct errors
*
* @return string
*/
public function getId() {
return md5($this->getMessage());
}
public function getTimestamp() {
return $this->_timestamp;
}
public function getType() {
return $this->_type;
}
public function getMessage() {
return $this->_message;
}
public function setTimestamp($timestamp) {
$this->_timestamp = $timestamp;
}
public function setType($type) {
$this->_type = $type;
}
public function setMessage($message) {
$this->_message = $message;
}
public function getIsNew() {
return $this->_isNew;
}
public function setIsNew($isNew) {
$this->_isNew = $isNew;
}
public function populate($data) {
foreach ($data as $prop => $value) {
if (property_exists($this, $prop)) {
$this->$prop = $value;
}
}
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
require_once 'LogReader/Item/Abstract.php';
class LogReader_Item_ApachePhp extends LogReader_Item_Abstract {
protected $_clientIp;
/**
*
* @var array
*/
protected $_stackTrace = array();
/**
*
* @var string
*/
protected $_referer = '';
public function getReferer() {
return $this->_referer;
}
public function setReferer($referer) {
$this->_referer = $referer;
}
/**
*
* @param string $line
*/
public function appendStackTrace($line) {
$this->_stackTrace[] = $line;
}
/**
*
* @return array
*/
public function getStackTrace() {
return $this->_stackTrace;
}
/**
*
* @param string $clientIp
*/
public function setClientIp($clientIp) {
$this->_clientIp = $clientIp;
}
/**
*
* @return string
*/
public function getClientIp() {
return $this->_clientIp;
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
require_once '../core/LogReader/Item/Abstract.php';
class LogReader_Item_Nginx extends LogReader_Item_Abstract {
/**
*
* @var string
*/
protected $_referrer = '';
/**
*
* @var string
*/
protected $_request = '';
/**
*
* @var string
*/
protected $_host = '';
public function getRequest() {
return $this->_request;
}
public function getHost() {
return $this->_host;
}
public function setRequest($request) {
$this->_request = $request;
}
public function setHost($host) {
$this->_host = $host;
}
public function getReferrer() {
return $this->_referrer;
}
public function setReferrer($referer) {
$this->_referrer = $referer;
}
public function getRequestUrl() {
$request = preg_replace('/^GET (.+) HTTP.+/', '$1', $this->getRequest());
$url = 'http://' . $this->getHost() . $request;
return $url;
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
require_once '../core/LogReader/Abstract.php';
require_once '../core/LogReader/Item/Nginx.php';
class LogReader_Nginx extends LogReader_Abstract {
public function read() {
//2014/03/28 15:17:15 [error] 13385#0: *197692 open() "/var/www/logo.png" failed (2: No such file or directory), client: 192.168.1.1, server: cs.google.com, request: "GET /static/img/logo.png HTTP/1.1", host: "cs.google.com", referrer: "http://google.com"
while (!$this->_file->eof()) {
if (preg_match('/^(?<date>[0-9\/]+ [0-9:]+) \[.+?\] .+? .+? (?<message>.+), client: .+?,(.+)request: "(?<request>.+)", host: "(?<host>.+?)"(, referrer: "(?<referrer>.+)")?/', $this->_file->fgets(), $matches)) {
$item = new LogReader_Item_Nginx();
$timestamp = date('Y-m-d H:i:s', strtotime($matches['date']));
$item->setTimestamp($timestamp);
$message = $matches['message'];
$type = $this->_getType($message);
$item->setType($type);
$item->setMessage($message);
$item->setRequest($matches['request']);
$item->setHost($matches['host']);
if (isset($matches['referrer'])) {
$item->setReferrer($matches['referrer']);
}
if ($this->_storage) {
$this->_storage->save($item);
}
}
}
}
protected function _getType($message) {
if (preg_match('/^([a-zA-Z0-9 ()]+) "/', $message, $matches) && isset($matches[1])) {
return trim($matches[1]);
}
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
require_once '../core/LogReader/Storage/Interface.php';
class LogReader_Storage_Array implements LogReader_Storage_Interface {
/**
*
* @var array
*/
protected $_data = array();
/**
*
* @return array
*/
public function load() {
return $this->_data;
}
public function save(\LogReader_Item_Abstract $item) {
$this->_data[] = $item;
}
/**
* Returns unique errors
*
* @return array
*/
public function loadUnique() {
$uniqRows = array();
foreach ($this->_data as $item) {
$itemId = $item->getId();
if (isset($uniqRows[$itemId])) {
$newTime = strtotime($item->getTimestamp());
$oldTime = strtotime($uniqRows[$itemId]->getTimestamp());
if ($newTime > $oldTime) {
$uniqRows[$itemId] = $item;
}
} else {
$uniqRows[$item->getId()] = $item;
}
}
uasort($uniqRows, function($a, $b) {
return strtotime($a->getTimestamp()) > strtotime($b->getTimestamp());
});
return $uniqRows;
}
}
+12
View File
@@ -0,0 +1,12 @@
<?php
require_once '../core/LogReader/Item/Abstract.php';
interface LogReader_Storage_Interface {
public function save(LogReader_Item_Abstract $item);
public function load();
public function loadUnique();
}
+492
View File
@@ -0,0 +1,492 @@
<?php
$path = realpath(__DIR__);
require_once $path.'/../core/main.php';
require_once ( $path.'/../core/ssp.class.php' );
// require_once (_DOCROOT_.'vendor/autoload.php');
require_once ($path.'/../vendor/autoload.php');
use Verot\Upload\Upload;
Class Mastermain {
public $title = '';
public $subtitle = '';
public $add_button = '';
public $edit_button = '';
public $delete_button = '';
public $table = '';
public $primaryKey = '';
public $select = '';
public $join = '';
public $where = '';
public $groupBy = '';
public $orderBy = '';
protected $render_html = '';
function __construct() {
global $db;
$args = func_get_args();
$this->add_button = '<button type="button" id="add_button" class="btn btn-sm btn-flat bg-info text-white btn-block"><i class="fa fa-plus"></i> Baru</button>';
$this->edit_button = '<button type="button" id="edit_button" class="btn btn-sm btn-flat bg-orange"><i class="fa fa-pencil"></i> Edit</button>';
$this->delete_button = '<button type="button" id="delete_button" class="btn btn-sm btn-flat btn-danger"><i class="fa fa-trash"></i> Hapus</button>';
}
public function view() {
$args = func_get_args();
if(array_key_exists(0, $args)) {
$view_file = $args[0];
}
else {
return false;
}
$this->render_html = $this->render($view_file, $args[1]);
if($args[2] == true) {
return $this->render_html;
}
else {
echo $this->render_html;
}
}
private function render()
{
$args = func_get_args();
if(count($args) > 0) {
$template = explode("/", $args[0]);
$file_name = end($template);
array_pop($template);
$folder = implode("/", $template);
$loader = new \Twig\Loader\FilesystemLoader(_DOCROOT_.$folder);
$twig = new \Twig\Environment($loader, [
'cache' => _DOCROOT_.'logs/cache',
]);
// $escaper = new \Twig\Extension\EscaperExtension('html');
// $twig->addExtension($escaper);
return $twig->render($file_name, $args[1]);
}
}
function add() {
if($this->table != '') {
$table = $this->table;
$args = func_get_args();
if(count($args) > 0) {
if(is_array($args[0])) {
$is_returning = (array_key_exists(1, $args)) ? $args[1] : false;
$returning_col = ($is_returning) ? $args[2] : false;
$query_returning = "";
if($returning_col != false) {
$query_returning = " RETURNING ".$returning_col;
}
$query = "INSERT INTO $table ".bind_sql($args[0]).$query_returning;
return execute($query);
}
else {
throw new Exception("Error Parameter Not Found", 1);
}
}
else {
throw new Exception("Error Parameter Not Found", 1);
}
}
else {
throw new Exception("Error Table Not Found", 1);
}
}
function edit() {
if($this->table != '') {
$table = $this->table;
$args = func_get_args();
if(count($args) > 0) {
if(is_array($args[0])) {
$update_condition = (array_key_exists(1, $args)) ? $args[1] : false;
if($update_condition != ''){
$query = "UPDATE $table ".bind_sql($args[0],1).' WHERE '.$update_condition;
return execute($query);
}
else {
throw new Exception("Error Where Condition Not Found", 1);
}
}
else {
throw new Exception("Error Parameter Not Found", 1);
}
}
else {
throw new Exception("Error Parameter Not Found", 1);
}
}
else {
throw new Exception("Error Table Not Found", 1);
}
}
function delete() {
if($this->table != '') {
$table = $this->table;
$args = func_get_args();
if(count($args) > 0) {
if(is_array($args[0])) {
$delete_condition = implode("\r\n",$args[0]);
if($delete_condition != ''){
$query = "DELETE FROM $table WHERE ".$delete_condition;
return execute($query);
}
else {
throw new Exception("Error Where Condition Not Found", 1);
}
}
else {
throw new Exception("Error Parameter Not Found", 1);
}
}
else {
throw new Exception("Error Parameter Not Found", 1);
}
}
else {
throw new Exception("Error Table Not Found", 1);
}
}
function check() {
global $db;
if($this->table != '') {
$table = $this->table;
$args = func_get_args();
if(count($args) > 0) {
if(is_array($args[0])) {
$check_condition = implode("\r\n",$args[0]);
if($check_condition != ''){
$query = "SELECT * FROM $table WHERE ".$check_condition;
$row_result = $db->query($query);
if($row_result->numRows() > 0)
{
return FALSE;
}
return TRUE;
}
else {
throw new Exception("Error Where Condition Not Found", 1);
}
}
else {
throw new Exception("Error Parameter Not Found", 1);
}
}
else {
throw new Exception("Error Parameter Not Found", 1);
}
}
else {
throw new Exception("Error Table Not Found", 1);
}
}
function soft_delete() {
if($this->table != '') {
$table = $this->table;
$args = func_get_args();
if(count($args) > 0) {
if(is_array($args[0])) {
$delete_condition = implode("\r\n",$args[0]);
if($delete_condition != ''){
$timestamp = date('Y-m-d H:i:s');
$query = "UPDATE $table SET deleted_at = '$timestamp' WHERE ".$delete_condition;
return execute($query);
}
else {
throw new Exception("Error Where Condition Not Found", 1);
}
}
else {
throw new Exception("Error Parameter Not Found", 1);
}
}
else {
throw new Exception("Error Parameter Not Found", 1);
}
}
else {
throw new Exception("Error Table Not Found", 1);
}
}
function datasource() {
global $db;
$args = func_get_args();
// get table
if($this->table != '') {
$table = $this->table;
}
else {
throw new Exception("Error Table Not Found", 1);
}
// get selected column
$columns = [];
if(is_array($this->select)) {
// $select = implode(", ",$this->select);
$column_inx = 0;
foreach($this->select as $field => $item) {
$arr_field = [];
if(is_array($item)) {
$arr_field = ['db'=>$field,'dt'=>$column_inx];
if(array_key_exists('format',$item)) {
$arr_field['formatter'] = $item['format'];
}
$columns[] = $arr_field;
}
else {
$columns[] = ['db'=>$field,'dt'=>$column_inx];
}
$column_inx++;
}
}
else {
// $select = $this->select;
// if($select == '') {
// $select = '*';
// }
}
// get join table
if(is_array($this->join)) {
$join = '';
foreach($this->join as $rel => $item) {
if(is_array($item)) {
$val = array_values($item);
$table_name = $rel;
if(count($val) > 1) {
$join_type = "\r\n".$val[1];
$join_condition = $val[0];
}
else {
$join_type = "\r\nJOIN ";
$join_condition = $val[0];
}
$join .= $join_type.' '.$table_name.' ON '.$join_condition;
}
else {
$join .= $item;
}
}
}
if($this->where != '') {
if(is_array($this->where)) {
$where = implode("\r\n", $this->where);
}
else {
$where = 'WHERE '.$this->where;
}
}
if($this->groupBy != '') {
if(is_array($this->groupBy)) {
$groupBy = 'GROUP BY '.implode("\r\n", $this->groupBy);
}
else {
$groupBy = 'GROUP BY '.$this->groupBy;
}
}
if($this->orderBy != '') {
if(is_array($this->orderBy)) {
$orderBy = 'ORDER BY '.implode("\r\n", $this->orderBy);
}
else {
$orderBy = 'ORDER BY '.$this->orderBy;
}
}
// Table's primary key
$primaryKey = $this->primaryKey;
// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
// SQL server connection information
$dbhost = $_ENV['POSTGRE_DB_HOST'];
$dbuser = $_ENV['POSTGRE_DB_USER'];
$dbpass = $_ENV['POSTGRE_DB_PASS'];
$dbname = $_ENV['POSTGRE_DB_NAME'];
$port = $_ENV['POSTGRE_DB_PORT'];
$sql_details = array(
'user' => $dbuser,
'pass' => $dbpass,
'db' => $dbname,
'host' => $dbhost,
'port' => $port
);
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* If you just want to use the basic configuration for DataTables with PHP
* server-side, there is no need to edit below this line.
*/
return json_encode(
SSP::complex( $args, $sql_details, $table, $join, $primaryKey, $columns , $where)
);
// $tmp_query = $db->query("SELECT $select FROM $table $join $where $groupBy $orderBy");
// $result['data'] = [];
// if($tmp_query->numRows() > 0) {
// foreach($tmp_query->fetchAll() as $row) {
// $result['data'][] = $row;
// }
// }
// return json_encode($result);
// exit;
}
private function strip_slash(&$value) {
if(is_array($value))
{
strip($value);
}
else {
$value = $value;
}
}
private function strip(&$request)
{
if(!is_array($request))
{
die("Inputan Bukan Array");
}
array_walk($request, "strip_slash");
return $request;
}
public function request() {
$wrap_request = [];
if(!empty($_REQUEST))
{
$getVar = $this->strip($_REQUEST);
if(!empty($getVar)) {
foreach($getVar as $k => $v) {
if(!array_key_exists($k, $wrap_request)) {
$wrap_request[$k] = $v;
}
}
}
}
if(!empty($_POST))
{
$getVar = $this->strip($_POST);
if(!empty($getVar)) {
foreach($getVar as $k => $v) {
if(!array_key_exists($k, $wrap_request)) {
$wrap_request[$k] = $v;
}
}
}
}
if(!empty($_GET))
{
$getVar = $this->strip($_GET);
if(!empty($getVar)) {
foreach($getVar as $k => $v) {
if(!array_key_exists($k, $wrap_request)) {
$wrap_request[$k] = $v;
}
}
}
}
return $wrap_request;
}
public function load_form(){
global $db;
}
public function file_save($file,$config){
global $path;
$base_upload_dir = './storage/';
// handle upload
$handle = new Upload($file);
$handle->file_max_size = (array_key_exists('file_max_size',$config)) ? $config['file_max_size'] : '8M';
$handle->allowed = (array_key_exists('allowed',$config)) ? $config['allowed'] : array('image/jpg','image/jpeg','image/png');
if($config['resize'])
{
$handle->image_resize = $config['resize'];
$handle->image_x = $config['image_x'];
$handle->image_y = $config['image_y'];
if(array_key_exists('image_ratio_y',$config) && $config['image_ratio_y'])
{
$handle->image_ratio_y = $config['image_ratio_y'];
}
if(array_key_exists('image_ratio_x',$config) && $config['image_ratio_x'])
{
$handle->image_ratio_x = $config['image_ratio_x'];
}
}
if ($handle->uploaded) {
$sub = (array_key_exists('storage_dir',$config)) ? $config['storage_dir'].'/' : '';
$sub_dir = makeDir($base_upload_dir.$sub,0777);
$handle->process($base_upload_dir.$sub);
if ($handle->processed) {
$handle->clean();
return $handle->file_dst_pathname;
} else {
log_message('error','Upload error '.$handle->error.". Dir ".$base_upload_dir.$sub);
throw new Exception("Error Upload : ".$handle->error.". Dir ".$base_upload_dir.$sub, 1);
return $handle->error;
}
}
else {
log_message('error','Upload error '.$handle->error.". Dir ".$base_upload_dir.$sub);
throw new Exception("Error Upload : ".$handle->error.". Dir ".$base_upload_dir.$sub, 1);
return false;
}
}
}
+1431
View File
File diff suppressed because it is too large Load Diff
+658
View File
@@ -0,0 +1,658 @@
<?php
/**
* Class SQLSRV_DataBase
*
* @version 0.2.0
* @license GPLv2
*/
class SQLServerDb {
/**
* The last ran query
*
* The last query is retained in case you want to do extended error handling in some way
*
* @since 0.1.0
* @access private
* @var string
*/
private $last_query = '';
/**
* The last Id from an sql->insert call
*
* @since 0.1.0
* @access private
* @var int
*/
private $last_insert_id = null;
/**
* Hold all errors encountered while processing a query/class construct
*
* @since 0.1.0
* @access private
* @var array
*/
private $error = array();
/**
* The database connection is held here
*
* @since 0.1.0
* @access private
* @var false|null|resource
*/
private $db = null;
/**
* The Database Schema is read into memory and kept here
*
* This is done because MSSQL is very picky about data types and containers, so if enabled
* the class will download the schema and keep it on hand to properly handle various data types
*
* @since 0.2.0
* @access private
* @var array|bool|mixed
*/
private $schema = false;
/**
* The storage location for the DB schema
*
* @since 0.2.0
* @access private
* @var null|string
*/
private $schema_location = null;
/**
* The numbrs of rows affected by a query
*
* @since 0.1.0
* @var int
*/
public $num_rows = 0;
/**
* If a query has returned any rows or not
*
* @since 0.1.0
* @var bool
*/
public $has_rows = false;
/**
* If a connection ot the database exists
*
* @since 0.1.0
* @var bool
*/
public $is_connected = false;
/**
* Database Username
*
* @since 0.1.0
* @access protected
* @var string
*/
protected $dbuser;
/**
* Database Password
*
* @since 0.1.0
* @access protected
* @var string
*/
protected $dbpassword;
/**
* Database Host
* @since 0.1.0
* @var string
*/
protected $dbhost;
/**
* Database Name
* @since 0.1.0
* @var string
*/
protected $dbname;
/**
* Database Port
* @since 0.1.0
* @var int
*/
protected $dbport;
/**
* SQLSRV_DataBase constructor.
*
* @since 0.1.0
* @since 0.2.0 Added the optional `$build_schema` parameter
*
* @param string $dbuser MSSQL database user
* @param string $dbpassword MSSQL database password
* @param string $dbname MSSQL database name
* @param string $dbhost MSSQL database host
* @param int $dbport MSSQL database port
* @param mixed $build_schema Where (if at all) to store the DB schema
*/
public function __construct( $dbuser, $dbpassword, $dbname, $dbhost, $dbport = 1433, $build_schema = false ) {
$this->dbuser = $dbuser;
$this->dbpassword = $dbpassword;
$this->dbname = $dbname;
$this->dbhost = $dbhost;
$this->dbport = $dbport;
$this->is_connected = $this->db_connect();
// If we've chosen to build a database schema, this is done on construct
if ( $this->is_connected && $build_schema ) {
if ( is_string( $build_schema ) ) {
$this->schema_location = $build_schema;
}
else {
// Set the schema store location to be alongside the DB class
$this->schema_location = dirname( __FILE__ );
}
$this->schema = $this->build_schema();
}
}
/**
* Connect to and select database
*
* @since 0.1.0
* @return bool
*/
public function db_connect() {
$serverName = "tcp:" . $this->dbhost . ", " . $this->dbport;
$connectionOptions = array(
"Database" => $this->dbname,
"UID" => $this->dbuser,
"PWD" => $this->dbpassword
);
// Create the connection resource
$this->db = sqlsrv_connect( $serverName, $connectionOptions );
// If the connection fails we get a false value and build our error log
if ( false === $this->db )
{
/*
* We don't use log_error() here as the values passed from a failed connection
* are not compatible with the errors passed from a failed query
*/
$error = sqlsrv_errors();
$this->error[] = $error;
error_log( 'Database failure: ' . print_r($error, true) );
return false;
}
sqlsrv_configure( 'WarningsReturnAsErrors', true );
return true;
}
/**
* Build the database schema based on table structures
*
* @param bool $force Force rewrite the schemas file
*
* @since 0.2.0
*
* @return array|bool|mixed
*/
private function build_schema( $force = false ) {
$schema_file = $this->schema_location . '/db-schema.php';
/*
* We return the data of the existing schema file if it exists and we aren't force re-writing it
*/
if ( file_exists( $schema_file ) && ! $force ) {
return json_decode( file_get_contents( $schema_file ) );
}
// Check if we can open the file location for writing
if ( ! $file = fopen( $schema_file, "w+" ) ) {
return false;
}
$schema = array();
$tables = $this->get_results( "
SELECT
TABLE_NAME
FROM
INFORMATION_SCHEMA.TABLES
WHERE
TABLE_TYPE = 'BASE TABLE'
AND
TABLE_CATALOG = '" . addslashes( DB_NAME ) . "'
" );
foreach( $tables AS $table ) {
$schema[ $table->TABLE_NAME ] = array();
$columns = $this->get_results( "
EXEC
sp_columns
" . $table->TABLE_NAME . "
" );
foreach( $columns AS $column ) {
$schema[ $table->TABLE_NAME ][ $column->COLUMN_NAME ] = $column;
}
}
fwrite( $file, json_encode( $schema ) );
fclose( $file );
return $schema;
}
/**
* Prepare values based on either the expected schema data (if it exists) or by what type of data it is
*
* @param string $table
* @param string $column
* @param mixed $value
*
* @since 0.2.0
*
* @return string
*/
private function schema_prepare_value( $table, $column, $value ) {
if ( false === $this->schema || ! isset( $this->schema->$table ) || ! isset( $this->schema->$table->$column ) ) {
if ( null === $value ) {
return 'NULL';
}
elseif ( ctype_digit( str_replace( array( '.' ), '', $value ) ) && substr_count( $value, '.' ) < 2 ) {
if(preg_match("/^0/",$value)) {
return "'".addslashes( utf8_decode( $value ) )."'";
}
else
return $value;
}
else {
return "'" . addslashes( utf8_decode( $value ) ) . "'";
}
}
$schema = $this->schema->$table->$column;
$numerics = array(
'int',
'decimal',
'money'
);
if ( in_array( $schema->TYPE_NAME, $numerics ) ) {
if ( null === $value || '' === $value ) {
if ( 1 == $schema->NULLABLE ) {
return 'NULL';
}
else {
return 0;
}
}
else {
return $value;
}
}
else {
if ( null === $value || empty( $value ) ) {
if ( 1 == $schema->NULLABLE ) {
return 'NULL';
}
else {
return "''";
}
}
}
return "'" . addslashes( utf8_decode( $value ) ) . "'";
}
/**
* Prepare the DB class for a new query
*
* @since 0.1.0
*
* @return void
*/
private function prepare() {
$this->error = array();
$this->last_insert_id = null;
$this->last_query = '';
$this->num_rows = 0;
$this->has_rows = false;
}
/**
* Log errors to the error container of the class and to the systems error log
*
* @param array $errors
*
* @since 0.1.0
*
* @return void
*/
private function log_error( $errors ) {
foreach( $errors AS $error ) {
$new_error = array(
'SQLSTATE' => $error['SQLSTATE'],
'code' => $error['code'],
'message' => $error['message'],
'query' => $this->last_query
);
error_log( var_export( $new_error, true ) );
$this->error[] = $new_error;
}
}
/**
* Update values in a table that matches the give ncriterias
*
* @param string $table
* @param array $what
* @param array $where
*
* @since 0.1.0
*
* @return void
*/
public function update( $table, $what, $where = array() ) {
$set = '';
$check = '';
foreach( $what AS $field => $value ) {
$field = trim( $field );
$value = trim( $value );
if ( ! empty( $set ) ) {
$set .= ', ';
}
$set .= $table . '.' . $field . ' = ';
$set .= $this->schema_prepare_value( $table, $field, $value );
}
foreach( $where AS $field => $value ) {
$check .= ' AND ' . $table . '.' . $field;
if ( null === $value ) {
$check .= ' IS NULL';
}
elseif ( ctype_digit( str_replace( array( '.', '-' ), '', $value ) ) && substr_count( $value, '.' ) < 2 ) {
$check .= ' = ' . $value;
}
else {
$check .= " = '" . addslashes( utf8_decode( $value ) ) . "'";
}
}
$result = $this->query( "
UPDATE
" . $table . "
SET
" . $set . "
WHERE
1 = 1
" . $check . "
", false );
}
/**
* Delete rows in a table based on the given criterias
*
* @param string $table
* @param array $where
*
* @since 0.1.0
*
* @return void
*/
public function delete( $table, $where = array() ) {
$check = '';
foreach( $where AS $field => $value ) {
$field = trim( $field );
$value = trim( $value );
$check .= ' AND ' . $table . '.' . $field;
if ( null === $value ) {
$check .= ' IS NULL';
}
if ( ctype_digit( str_replace( array( '.', '-' ), '', $value ) ) && substr_count( $value, '.' ) < 2 ) {
$check .= ' = ' . $value;
}
else {
$check .= " = '" . addslashes( utf8_decode( $value ) ) . "'";
}
}
$result = $this->query( "
DELETE FROM
" . $table . "
WHERE
1 = 1
" . $check . "
", false );
}
/**
* Insert a new row and populate it with the given values
*
* @param string $table
* @param array $data
*
* @since 0.1.0
*
* @return void
*/
public function insert( $table, $data ) {
$fields = '';
$values = '';
foreach( $data AS $field => $value ) {
$field = trim( $field );
$value = trim( $value );
if ( ! empty( $fields ) ) {
$fields .= ', ';
}
if ( ! empty( $values ) ) {
$values .= ', ';
}
$fields .= $table . '.' . $field;
$values .= $this->schema_prepare_value( $table, $field, $value );
}
$result = $this->query( "
INSERT INTO
" . $table . " ( " . $fields . " )
VALUES ( " . $values . " )
", false );
}
/**
* Get a single row from the database and return it in the given format
*
* @param string $query
* @param string $format
*
* @since 0.1.0
*
* @return array|bool|null|object
*/
public function get_row( $query, $format = 'object' ) {
$request = $this->query( $query );
if ( ! $this->has_error() ) {
if ( 'array' == $format ) {
$response = sqlsrv_fetch_array( $request, SQLSRV_FETCH_ASSOC );
}
else {
$response = sqlsrv_fetch_object( $request );
}
}
else {
$response = false;
}
return $response;
}
/**
* Get all the rows returned by a query to the database
*
* @param string $query
* @param string $format
*
* @since 0.1.0
*
* @return array|bool
*/
public function get_results( $query, $format = 'object' ) {
$response = array();
$request = $this->query( $query );
if ( $this->has_error() ) {
$response = false;
}
else {
if ( 'array' == $format ) {
while ( $answer = sqlsrv_fetch_array( $request, SQLSRV_FETCH_ASSOC ) ) {
$response[] = $answer;
}
}
else {
while ( $answer = sqlsrv_fetch_object( $request ) ) {
$response[] = $answer;
}
}
}
return $response;
}
/**
* Return the primary index value from a table
*
* @since 0.2.0
*
* @return bool|int
*/
public function last_insert_id() {
if ( $this->has_error() || empty( $this->last_query ) ) {
return false;
}
if ( empty( $this->last_insert_id ) ) {
$this->last_insert_id = $this->get_row( "SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]" );
}
return $this->last_insert_id->SCOPE_IDENTITY;
}
/**
* @since 0.1.0
* @deprecated 0.2.0 Use last_insert_id()
* @see last_insert_id()
*
* @return bool|int
*/
public function get_last_id() {
return $this->last_insert_id();
}
/**
* Runs the actual query against the database
*
* @param string $query
* @param bool $can_get_rows
*
* @since 0.1.0
*
* @return bool|resource
*/
public function query( $query, $can_get_rows = true ) {
// If no connection is found we try to restore it
if ( ! $this->is_connected ) {
$this->is_connected = $this->db_connect();
// If we couldn't reconnect we break out early
if ( ! $this->is_connected ) {
return false;
}
}
$this->prepare();
$this->last_query = $query;
$doing_query = sqlsrv_query( $this->db, $query );
if ( false === $doing_query ) {
if ( null != ( $errors = sqlsrv_errors() ) ) {
$this->log_error( $errors );
}
}
else {
$this->has_rows = true;
$this->num_rows = sqlsrv_num_rows( $doing_query );
}
if ( $can_get_rows ) {
if ( sqlsrv_has_rows( $doing_query ) ) {
$this->has_rows = true;
} else {
$this->has_rows = false;
}
}
return $doing_query;
}
/**
* Return a list of errors encountered on the last query, or false
*
* @since 0.2.0
*
* @return array|bool
*/
public function has_error() {
if ( ! empty( $this->error ) ) {
return $this->error;
}
return false;
}
/**
* @since 0.1.0
* @deprecated 0.2.0 Use has_error() instead
* @see has_error()
*
* @return array|bool
*/
public function hasError() {
return $this->has_error();
}
/**
* Return the last ran query in its entirety
*
* @since 0.1.0
*
* @return string
*/
public function get_last_query() {
return $this->last_query;
}
}
+540
View File
@@ -0,0 +1,540 @@
<?php
class Ssp {
/**
* Create the data output array for the DataTables rows
*
* @param array $columns Column information array
* @param array $data Data from the SQL get
* @return array Formatted data in a row based format
*/
static function data_output ( $columns, $data )
{
$out = array();
// self::debug($data);
for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) {
$row = array();
for ( $j=0, $jen=count($columns) ; $j<$jen ; $j++ ) {
$column = $columns[$j];
$column['db'] = self::change_column($column['db']);
$columns[$j]['db'] = self::change_column($columns[$j]['db']);
// Is there a formatter?
if ( isset( $column['formatter'] ) ) {
$row[ $column['db'] ] = $column['formatter']( $data[$i][ $column['db'] ], $data[$i] );
}
else {
$row[ $column['db'] ] = $data[$i][ $columns[$j]['db'] ];
}
}
$out[] = $row;
}
return $out;
}
/**
* Database connection
*
* Obtain an PHP PDO connection from a connection details array
*
* @param array $conn SQL connection details. The array should have
* the following properties
* * host - host name
* * db - database name
* * user - user name
* * pass - user password
* @return resource PDO connection
*/
static function db ( $conn )
{
if ( is_array( $conn ) ) {
return self::sql_connect( $conn );
}
return $conn;
}
/**
* Paging
*
* Construct the LIMIT clause for server-side processing SQL query
*
* @param array $request Data sent to server by DataTables
* @param array $columns Column information array
* @return string SQL limit clause
*/
static function limit ( $request, $columns )
{
$limit = '';
if ( isset($request['start']) && $request['length'] != -1 ) {
$limit = "LIMIT ".intval($request['start']).", ".intval($request['length']);
}
return $limit;
}
/**
* Ordering
*
* Construct the ORDER BY clause for server-side processing SQL query
*
* @param array $request Data sent to server by DataTables
* @param array $columns Column information array
* @return string SQL order by clause
*/
static function order ( $request, $columns )
{
$order = '';
if ( isset($request['order']) && count($request['order']) ) {
$orderBy = array();
$dtColumns = self::pluck( $columns, 'dt' );
for ( $i=0, $ien=count($request['order']) ; $i<$ien ; $i++ ) {
// Convert the column index into the column data property
$columnIdx = intval($request['order'][$i]['column']);
$requestColumn = $request['columns'][$columnIdx];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
if ( $requestColumn['orderable'] == 'true' ) {
$dir = $request['order'][$i]['dir'] === 'asc' ?
'ASC' :
'DESC';
$column['db'] = (preg_match("/ as /i", $column['db'])) ? self::change_column($column['db']) : $column['db'];
$orderBy[] = '`'.$column['db'].'` '.$dir;
}
}
$order = 'ORDER BY '.implode(', ', $orderBy);
}
return $order;
}
/**
* Searching / Filtering
*
* Construct the WHERE clause for server-side processing SQL query.
*
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here performance on large
* databases would be very poor
*
* @param array $request Data sent to server by DataTables
* @param array $columns Column information array
* @param array $bindings Array of values for PDO bindings, used in the
* sql_exec() function
* @return string SQL where clause
*/
static function filter ( $request, $columns, &$bindings )
{
$globalSearch = array();
$columnSearch = array();
$dtColumns = self::pluck( $columns, 'dt' );
if ( isset($request['search']) && $request['search']['value'] != '' ) {
$str = $request['search']['value'];
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
$requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
// $column['db'] = (preg_match("/ as /i", $column['db'])) ? self::change_column($column['db']) : $column['db'];
if(preg_match("/ as /i", $column['db']))
{
$exp_column = explode(' as ', $column['db']);
$column['db'] = $exp_column[0];
}
if ( $requestColumn['searchable'] == 'true' ) {
$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
// $globalSearch[] = "`".$column['db']."` LIKE ".$binding;
$globalSearch[] = "".$column['db']." LIKE '%".$str."%'";
}
}
}
// Individual column filtering
// self::debug($request);
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
$requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
$column['db'] = (preg_match("/ as /i", $column['db'])) ? self::change_column($column['db']) : $column['db'];
$str = $requestColumn['search']['value'];
if ( $requestColumn['searchable'] == 'true' &&
$str != '' ) {
$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
$columnSearch[] = "`".$column['db']."` LIKE ".$binding;
}
}
// Combine the filters into a single string
$where = '';
if ( count( $globalSearch ) ) {
$where = '('.implode(' OR ', $globalSearch).')';
}
if ( count( $columnSearch ) ) {
$where = $where === '' ?
implode(' AND ', $columnSearch) :
$where .' AND '. implode(' AND ', $columnSearch);
}
if ( $where !== '' ) {
$where = 'WHERE '.$where;
}
return $where;
}
/**
* Perform the SQL queries needed for an server-side processing requested,
* utilising the helper functions of this class, limit(), order() and
* filter() among others. The returned array is ready to be encoded as JSON
* in response to an SSP request, or can be modified if needed before
* sending back to the client.
*
* @param array $request Data sent to server by DataTables
* @param array|PDO $conn PDO connection resource or connection parameters array
* @param string $table SQL table to query
* @param string $join SQL join table to query
* @param string $primaryKey Primary key of the table
* @param array $columns Column information array
* @return array Server-side processing response array
*/
static function simple ( $request, $conn, $table, $join, $primaryKey, $columns )
{
$bindings = array();
$db = self::db( $conn );
// Build the SQL query string from the request
$limit = self::limit( $request, $columns );
$order = self::order( $request, $columns );
$where = self::filter( $request, $columns, $bindings );
// Main query to actually get the data
$data = self::sql_exec( $db, $bindings,
"SELECT SQL_CALC_FOUND_ROWS ".implode(", ", self::pluck($columns, 'db'))."
FROM `$table`
$join
$where
$order
$limit"
);
// Data set length after filtering
$resFilterLength = self::sql_exec( $db,
"SELECT FOUND_ROWS()"
);
$recordsFiltered = $resFilterLength[0][0];
// Total data set length
$resTotalLength = self::sql_exec( $db,
"SELECT COUNT(`{$primaryKey}`)
FROM `$table`
$join
"
);
$recordsTotal = $resTotalLength[0][0];
/*
* Output
*/
return array(
"draw" => intval( $request['draw'] ),
"recordsTotal" => intval( $recordsTotal ),
"recordsFiltered" => intval( $recordsFiltered ),
"data" => self::data_output( $columns, $data )
);
}
/**
* The difference between this method and the `simple` one, is that you can
* apply additional `where` conditions to the SQL queries. These can be in
* one of two forms:
*
* * 'Result condition' - This is applied to the result set, but not the
* overall paging information query - i.e. it will not effect the number
* of records that a user sees they can have access to. This should be
* used when you want apply a filtering condition that the user has sent.
* * 'All condition' - This is applied to all queries that are made and
* reduces the number of records that the user can access. This should be
* used in conditions where you don't want the user to ever have access to
* particular records (for example, restricting by a login id).
*
* @param array $request Data sent to server by DataTables
* @param array|PDO $conn PDO connection resource or connection parameters array
* @param string $table SQL table to query
* @param string $primaryKey Primary key of the table
* @param array $columns Column information array
* @param string $whereResult WHERE condition to apply to the result set
* @param string $whereAll WHERE condition to apply to all queries
* @return array Server-side processing response array
*/
static function complex ( $request, $conn, $table, $join, $primaryKey, $columns, $whereResult=null, $whereAll=null )
{
$bindings = array();
$db = self::db( $conn );
$localWhereResult = array();
$localWhereAll = array();
$whereAllSql = '';
// Build the SQL query string from the request
$limit = self::limit( $request, $columns );
$order = self::order( $request, $columns );
$where = self::filter( $request, $columns, $bindings );
$whereResult = self::_flatten( $whereResult );
$whereAll = self::_flatten( $whereAll );
if ( $whereResult ) {
$where = $where ?
$where .' AND '.$whereResult :
'WHERE '.$whereResult;
}
if ( $whereAll ) {
$where = $where ?
$where .' AND '.$whereAll :
'WHERE '.$whereAll;
$whereAllSql = 'WHERE '.$whereAll;
}
// Main query to actually get the data
$data = self::sql_exec( $db, $bindings,
"SELECT SQL_CALC_FOUND_ROWS ".implode(", ", self::pluck($columns, 'db'))."
FROM `$table`
$join
$where
$order
$limit"
);
// Data set length after filtering
$resFilterLength = self::sql_exec( $db,
"SELECT FOUND_ROWS()"
);
$recordsFiltered = $resFilterLength[0][0];
// Total data set length
$resTotalLength = self::sql_exec( $db, $bindings,
"SELECT COUNT(`{$primaryKey}`)
FROM `$table`
$join ".
$whereAllSql
);
$recordsTotal = $resTotalLength[0][0];
/*
* Output
*/
return array(
"draw" => intval( $request['draw'] ),
"recordsTotal" => intval( $recordsTotal ),
"recordsFiltered" => intval( $recordsFiltered ),
"data" => self::data_output( $columns, $data )
);
}
/**
* Connect to the database
*
* @param array $sql_details SQL server connection details array, with the
* properties:
* * host - host name
* * db - database name
* * user - user name
* * pass - user password
* @return resource Database connection handle
*/
static function sql_connect ( $sql_details )
{
try {
$db = @new PDO(
"mysql:host={$sql_details['host']};dbname={$sql_details['db']}",
$sql_details['user'],
$sql_details['pass'],
array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION )
);
}
catch (PDOException $e) {
self::fatal(
"An error occurred while connecting to the database. ".
"The error reported by the server was: ".$e->getMessage()
);
}
return $db;
}
/**
* Execute an SQL query on the database
*
* @param resource $db Database handler
* @param array $bindings Array of PDO binding values from bind() to be
* used for safely escaping strings. Note that this can be given as the
* SQL query string if no bindings are required.
* @param string $sql SQL query to execute.
* @return array Result from the query (all rows)
*/
static function sql_exec ( $db, $bindings, $sql=null )
{
// Argument shifting
if ( $sql === null ) {
$sql = $bindings;
}
$stmt = $db->prepare( $sql );
// echo $sql.'<br>';
// Bind parameters
if ( is_array( $bindings ) ) {
for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) {
$binding = $bindings[$i];
$stmt->bindValue( $binding['key'], $binding['val'], $binding['type'] );
}
}
// Execute
try {
$stmt->execute();
}
catch (PDOException $e) {
// self::debug($sql);
self::fatal( "An SQL error occurred: ".$e->getMessage()."\r\nSQL : ".$sql );
}
// Return all
return $stmt->fetchAll();
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Internal methods
*/
/**
* Throw a fatal error.
*
* This writes out an error message in a JSON string which DataTables will
* see and show to the user in the browser.
*
* @param string $msg Message to send to the client
*/
static function fatal ( $msg )
{
echo json_encode( array(
"error" => $msg
) );
exit(0);
}
/**
* Create a PDO binding key which can be used for escaping variables safely
* when executing a query with sql_exec()
*
* @param array &$a Array of bindings
* @param * $val Value to bind
* @param int $type PDO field type
* @return string Bound key to be used in the SQL where this parameter
* would be used.
*/
static function bind ( &$a, $val, $type )
{
$key = ':binding_'.count( $a );
$a[] = array(
'key' => $key,
'val' => $val,
'type' => $type
);
return $key;
}
/**
* Pull a particular property from each assoc. array in a numeric array,
* returning and array of the property values from each item.
*
* @param array $a Array to get data from
* @param string $prop Property to read
* @return array Array of property values
*/
static function pluck ( $a, $prop )
{
$out = array();
for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
$out[] = $a[$i][$prop];
}
return $out;
}
/**
* Return a string from an array or a string
*
* @param array|string $a Array to join
* @param string $join Glue for the concatenation
* @return string Joined string
*/
static function _flatten ( $a, $join = ' AND ' )
{
if ( ! $a ) {
return '';
}
else if ( $a && is_array($a) ) {
return implode( $join, $a );
}
return $a;
}
static function debug($variable, $is_die = FALSE)
{
echo "<pre>";
print_r($variable);
echo "</pre>";
if ($is_die)
{
die();
}
}
static function change_column($column_name)
{
// Spesial treatment to show row data
if (preg_match("/\./", $column_name))
{
$exp_column = explode(".", $column_name);
$column_name = end($exp_column);
}
if (preg_match("/ as /i", $column_name))
{
$exp_column = explode(" as ",$column_name);
$column_name = end($exp_column);
}
return $column_name;
}
}
?>
+536
View File
@@ -0,0 +1,536 @@
<?php
class Ssp {
var $rowCount = 0;
/**
* Create the data output array for the DataTables rows
*
* @param array $columns Column information array
* @param array $data Data from the SQL get
* @return array Formatted data in a row based format
*/
static function data_output ( $columns, $data )
{
$out = array();
// self::debug($data);
for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) {
$row = array();
for ( $j=0, $jen=count($columns) ; $j<$jen ; $j++ ) {
$column = $columns[$j];
$column['db'] = self::change_column($column['db']);
$columns[$j]['db'] = self::change_column($columns[$j]['db']);
// Is there a formatter?
if ( isset( $column['formatter'] ) ) {
$row[ $column['db'] ] = $column['formatter']( $data[$i][ $column['db'] ], $data[$i] );
}
else {
$row[ $column['db'] ] = $data[$i][ $columns[$j]['db'] ];
}
}
$out[] = $row;
}
return $out;
}
/**
* Database connection
*
* Obtain an PHP PDO connection from a connection details array
*
* @param array $conn SQL connection details. The array should have
* the following properties
* * host - host name
* * db - database name
* * user - user name
* * pass - user password
* @return resource PDO connection
*/
static function db ( $conn )
{
if ( is_array( $conn ) ) {
return self::sql_connect( $conn );
}
return $conn;
}
/**
* Paging
*
* Construct the LIMIT clause for server-side processing SQL query
*
* @param array $request Data sent to server by DataTables
* @param array $columns Column information array
* @return string SQL limit clause
*/
static function limit ( $request, $columns )
{
$limit = '';
if ( isset($request['start']) && $request['length'] != -1 ) {
$limit = "OFFSET ".intval($request['start'])." LIMIT ".intval($request['length']);
}
return $limit;
}
/**
* Ordering
*
* Construct the ORDER BY clause for server-side processing SQL query
*
* @param array $request Data sent to server by DataTables
* @param array $columns Column information array
* @return string SQL order by clause
*/
static function order ( $request, $columns )
{
$order = '';
if ( isset($request['order']) && count($request['order']) ) {
$orderBy = array();
$dtColumns = self::pluck( $columns, 'dt' );
for ( $i=0, $ien=count($request['order']) ; $i<$ien ; $i++ ) {
// Convert the column index into the column data property
$columnIdx = intval($request['order'][$i]['column']);
$requestColumn = $request['columns'][$columnIdx];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
if ( $requestColumn['orderable'] == 'true' ) {
$dir = $request['order'][$i]['dir'] === 'asc' ?
'ASC' :
'DESC';
$column['db'] = (preg_match("/ as /i", $column['db'])) ? self::change_column($column['db']) : $column['db'];
$orderBy[] = $column['db'].' '.$dir;
}
}
$order = 'ORDER BY '.implode(', ', $orderBy);
}
return $order;
}
/**
* Searching / Filtering
*
* Construct the WHERE clause for server-side processing SQL query.
*
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here performance on large
* databases would be very poor
*
* @param array $request Data sent to server by DataTables
* @param array $columns Column information array
* @param array $bindings Array of values for PDO bindings, used in the
* sql_exec() function
* @return string SQL where clause
*/
static function filter ( $request, $columns, &$bindings )
{
$globalSearch = array();
$columnSearch = array();
$dtColumns = self::pluck( $columns, 'dt' );
if ( isset($request['search']) && $request['search']['value'] != '' ) {
$str = $request['search']['value'];
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
$requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
// $column['db'] = (preg_match("/ as /i", $column['db'])) ? self::change_column($column['db']) : $column['db'];
if(preg_match("/ as /i", $column['db']))
{
$exp_column = explode(' as ', $column['db']);
$column['db'] = $exp_column[0];
}
if ( $requestColumn['searchable'] == 'true' ) {
$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
$globalSearch[] = "".$column['db']." LIKE '%".$str."%'";
}
}
}
// Individual column filtering
// self::debug($request);
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
$requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
$column['db'] = (preg_match("/ as /i", $column['db'])) ? self::change_column($column['db']) : $column['db'];
$str = $requestColumn['search']['value'];
if ( $requestColumn['searchable'] == 'true' &&
$str != '' ) {
$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
$columnSearch[] = $column['db']." LIKE ".$binding;
}
}
// Combine the filters into a single string
$where = '';
if ( count( $globalSearch ) ) {
$where = '('.implode(' OR ', $globalSearch).')';
}
if ( count( $columnSearch ) ) {
$where = $where === '' ?
implode(' AND ', $columnSearch) :
$where .' AND '. implode(' AND ', $columnSearch);
}
if ( $where !== '' ) {
$where = 'WHERE '.$where;
}
return $where;
}
/**
* Perform the SQL queries needed for an server-side processing requested,
* utilising the helper functions of this class, limit(), order() and
* filter() among others. The returned array is ready to be encoded as JSON
* in response to an SSP request, or can be modified if needed before
* sending back to the client.
*
* @param array $request Data sent to server by DataTables
* @param array|PDO $conn PDO connection resource or connection parameters array
* @param string $table SQL table to query
* @param string $join SQL join table to query
* @param string $primaryKey Primary key of the table
* @param array $columns Column information array
* @return array Server-side processing response array
*/
static function simple ( $request, $conn, $table, $join, $primaryKey, $columns )
{
$bindings = array();
$db = self::db( $conn );
// Build the SQL query string from the request
$limit = self::limit( $request, $columns );
$order = self::order( $request, $columns );
$where = self::filter( $request, $columns, $bindings );
// Main query to actually get the data
$data = self::sql_exec( $db, $bindings,
"SELECT ".implode(", ", self::pluck($columns, 'db'))."
FROM $table
$join
$where
$order
$limit"
);
// Data set length after filtering
$recordsFiltered = $this->rowCount;
// Total data set length
$resTotalLength = self::sql_exec( $db,
"SELECT COUNT({$primaryKey})
FROM $table
$join "
);
$recordsTotal = $resTotalLength[0][0];
/*
* Output
*/
return array(
"draw" => intval( $request['draw'] ),
"recordsTotal" => intval( $recordsTotal ),
"recordsFiltered" => intval( $recordsFiltered ),
"data" => self::data_output( $columns, $data )
);
}
/**
* The difference between this method and the `simple` one, is that you can
* apply additional `where` conditions to the SQL queries. These can be in
* one of two forms:
*
* * 'Result condition' - This is applied to the result set, but not the
* overall paging information query - i.e. it will not effect the number
* of records that a user sees they can have access to. This should be
* used when you want apply a filtering condition that the user has sent.
* * 'All condition' - This is applied to all queries that are made and
* reduces the number of records that the user can access. This should be
* used in conditions where you don't want the user to ever have access to
* particular records (for example, restricting by a login id).
*
* @param array $request Data sent to server by DataTables
* @param array|PDO $conn PDO connection resource or connection parameters array
* @param string $table SQL table to query
* @param string $primaryKey Primary key of the table
* @param array $columns Column information array
* @param string $whereResult WHERE condition to apply to the result set
* @param string $whereAll WHERE condition to apply to all queries
* @return array Server-side processing response array
*/
static function complex ( $request, $conn, $table, $join, $primaryKey, $columns, $whereResult=null, $whereAll=null )
{
$bindings = array();
$db = self::db( $conn );
$localWhereResult = array();
$localWhereAll = array();
$whereAllSql = '';
// Build the SQL query string from the request
$limit = self::limit( $request, $columns );
$order = self::order( $request, $columns );
$where = self::filter( $request, $columns, $bindings );
$whereResult = self::_flatten( $whereResult );
$whereAll = self::_flatten( $whereAll );
if ( $whereResult ) {
$where = $where ?
$where .' AND '.$whereResult :
'WHERE '.$whereResult;
}
if ( $whereAll ) {
$where = $where ?
$where .' AND '.$whereAll :
'WHERE '.$whereAll;
$whereAllSql = 'WHERE '.$whereAll;
}
// Main query to actually get the data
$data = self::sql_exec( $db, $bindings,
"SELECT ".implode(", ", self::pluck($columns, 'db'))."
FROM $table
$join
$where
$order
$limit"
);
// Data set length after filtering
$recordsFiltered = $this->rowCount;
// Total data set length
$resTotalLength = self::sql_exec( $db, $bindings,
"SELECT COUNT({$primaryKey})
FROM $table
$join ".
$whereAllSql
);
$recordsTotal = $resTotalLength[0][0];
/*
* Output
*/
return array(
"draw" => intval( $request['draw'] ),
"recordsTotal" => intval( $recordsTotal ),
"recordsFiltered" => intval( $recordsFiltered ),
"data" => self::data_output( $columns, $data )
);
}
/**
* Connect to the database
*
* @param array $sql_details Postgre server connection details array, with the
* properties:
* * host - host name
* * port - port number
* * db - database name
* * user - user name
* * pass - user password
* @return resource Database connection handle
*/
static function sql_connect ( $sql_details )
{
try {
$db = @new PDO(
"pgsql:host={$sql_details['host']} port={$sql_details['port']} dbname={$sql_details['db']} options='--client_encoding=UTF8'",
$sql_details['user'],
$sql_details['pass'],
array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION )
);
}
catch (PDOException $e) {
self::fatal(
"An error occurred while connecting to the database. ".
"The error reported by the server was: ".$e->getMessage()
);
}
return $db;
}
/**
* Execute an SQL query on the database
*
* @param resource $db Database handler
* @param array $bindings Array of PDO binding values from bind() to be
* used for safely escaping strings. Note that this can be given as the
* SQL query string if no bindings are required.
* @param string $sql SQL query to execute.
* @return array Result from the query (all rows)
*/
static function sql_exec ( $db, $bindings, $sql=null )
{
// Argument shifting
if ( $sql === null ) {
$sql = $bindings;
}
$stmt = $db->prepare( $sql );
// echo $sql.'<br>';
// Bind parameters
if ( is_array( $bindings ) ) {
for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) {
$binding = $bindings[$i];
$stmt->bindValue( $binding['key'], $binding['val'], $binding['type'] );
}
}
// Execute
try {
$stmt->execute();
$this->rowCount = $stmt->rowCount();
}
catch (PDOException $e) {
// self::debug($sql);
self::fatal( "An SQL error occurred: ".$e->getMessage()."\r\nSQL : ".$sql );
}
// Return all
return $stmt->fetchAll();
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Internal methods
*/
/**
* Throw a fatal error.
*
* This writes out an error message in a JSON string which DataTables will
* see and show to the user in the browser.
*
* @param string $msg Message to send to the client
*/
static function fatal ( $msg )
{
echo json_encode( array(
"error" => $msg
) );
exit(0);
}
/**
* Create a PDO binding key which can be used for escaping variables safely
* when executing a query with sql_exec()
*
* @param array &$a Array of bindings
* @param * $val Value to bind
* @param int $type PDO field type
* @return string Bound key to be used in the SQL where this parameter
* would be used.
*/
static function bind ( &$a, $val, $type )
{
$key = ':binding_'.count( $a );
$a[] = array(
'key' => $key,
'val' => $val,
'type' => $type
);
return $key;
}
/**
* Pull a particular property from each assoc. array in a numeric array,
* returning and array of the property values from each item.
*
* @param array $a Array to get data from
* @param string $prop Property to read
* @return array Array of property values
*/
static function pluck ( $a, $prop )
{
$out = array();
for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
$out[] = $a[$i][$prop];
}
return $out;
}
/**
* Return a string from an array or a string
*
* @param array|string $a Array to join
* @param string $join Glue for the concatenation
* @return string Joined string
*/
static function _flatten ( $a, $join = ' AND ' )
{
if ( ! $a ) {
return '';
}
else if ( $a && is_array($a) ) {
return implode( $join, $a );
}
return $a;
}
static function debug($variable, $is_die = FALSE)
{
echo "<pre>";
print_r($variable);
echo "</pre>";
if ($is_die)
{
die();
}
}
static function change_column($column_name)
{
// Spesial treatment to show row data
if (preg_match("/\./", $column_name))
{
$exp_column = explode(".", $column_name);
$column_name = end($exp_column);
}
if (preg_match("/ as /i", $column_name))
{
$exp_column = explode(" as ",$column_name);
$column_name = end($exp_column);
}
return $column_name;
}
}
?>
+58
View File
@@ -0,0 +1,58 @@
<?php
if(!session_id()) {
session_start();
}
require_once 'main.php';
use GuzzleHttp\Client;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\RequestException;
$dotenv = new Dotenv\Dotenv(_DOCROOT_);
$dotenv->load();
if(!array_key_exists('method', $_REQUEST)) {
echo 'Failed! Method doesnt exist.';
exit;
}
if(!array_key_exists('url', $_REQUEST)) {
echo 'Failed! Url requested doesnt exist.';
exit;
}
$main_url = $_ENV['BILLING_DB_URL'];
$url_request = $main_url.$_REQUEST['url'];
$method = $_REQUEST['method'];
$object_only = (array_key_exists('object_only', $_REQUEST)) ? $_REQUEST['object_only'] : FALSE;
if($method == 'GET') {
$content_type = 'application/json; charset=utf-8';
}
elseif($method == 'POST' || $method == 'PUT') {
$content_type = 'application/x-www-form-urlencoded';
}
$client = new GuzzleHttp\Client();
$request = new Request(
$method, // GET,POST,PUT
$url_request, // URL
[
'Accept' => 'application/json',
'Content-type' => $content_type
],
$body // Post / Put Body (text)
);
$obj_request = $client->send($request);
$json_request = ($obj_request->getStatusCode() == 200) ? $obj_request->getBody()->getContents() : [];
if($object_only == TRUE) {
echo $json_request;
}
else {
// echo (array) json_decode($json_request);
echo $json_request;
}
+212
View File
@@ -0,0 +1,212 @@
<?php
require_once _DOCROOT_.'vendor/autoload.php';
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\FirePHPHandler;
$dotenv = new Dotenv\Dotenv(_DOCROOT_);
$dotenv->load();
class db {
protected $connection;
protected $stmt;
public $insertid;
public $num_rows;
public $result_metadata;
public $result_fetch;
public $fetch_field;
public $query_count = 0;
public $debugging = FALSE;
public $error;
public function __construct($dbhost = '', $dbuser = '', $dbpass = '', $dbname = '', $charset = 'utf8') {
if($dbhost == '' || $dbuser == '' || $dbpass == '' || $dbname == '')
{
$dbhost = 'p:'.$_ENV['DATABASE_HOST'];
$dbuser = $_ENV['DATABASE_USER'];
$dbpass = $_ENV['DATABASE_PASS'];
$dbname = $_ENV['DATABASE_NAME'];
}
$this->connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($this->connection->connect_error) {
$this->debug('Failed to connect to MySQL - ' . $this->connection->connect_error);
}
$this->connection->set_charset($charset);
}
private function makeDir($new_path, $mode) {
return is_dir($new_path) || mkdir($new_path, $mode, true);
}
public function debug($args,$type = 'debug') {
global $logdir;
// create a log channel
$logger = new Logger('query');
$daily_log = date('d-m-Y').'.log';
$year_dir = self::makeDir($logdir.'activity/'.date('Y'),0777);
$month_dir = self::makeDir($logdir.'activity/'.date('Y').'/'.date('m'),0777);
$dir_log = $logdir.'activity/'.date('Y').'/'.date('m').'/'.$daily_log;
$logger->pushHandler(new StreamHandler($dir_log, Logger::DEBUG));
$uri = $_SERVER['REQUEST_URI'];
$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$query = $_SERVER['QUERY_STRING'];
if(!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip=$_SERVER['HTTP_CLIENT_IP']; // share internet
} elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip=$_SERVER['HTTP_X_FORWARDED_FOR']; // pass from proxy
} else {
$ip=$_SERVER['REMOTE_ADDR'];
}
if($type == 'debug'){
$logger->addDebug($args,[$_SESSION['NAMA_PEGAWAI'],$url,$query,$ip]);
}
elseif($type == 'info'){
$logger->addInfo($args,[$_SESSION['NAMA_PEGAWAI'],$url,$query,$ip]);
}
}
public function query($query) {
if ($this->stmt = $this->connection->prepare($query)) {
if (func_num_args() > 1) {
$x = func_get_args();
$args = array_slice($x, 1);
$types = '';
$args_ref = array();
foreach ($args as $k => &$arg) {
if (is_array($args[$k])) {
foreach ($args[$k] as $j => &$a) {
$types .= $this->_gettype($args[$k][$j]);
$args_ref[] = &$a;
}
} else {
$types .= $this->_gettype($args[$k]);
$args_ref[] = &$arg;
}
}
array_unshift($args_ref, $types);
call_user_func_array(array($this->stmt, 'bind_param'), $args_ref);
}
if($this->debugging == TRUE)
{
$this->debug($query,'info');
}
$this->stmt->execute();
$this->insertid = $this->stmt->insert_id;
if($this->stmt->result_metadata()){
$this->stmt->store_result();
$this->num_rows = $this->stmt->num_rows;
$this->result_metadata = $this->stmt->result_metadata();
$params = array();
$meta = $this->result_metadata;
$this->fetch_field = [];
while ($field = $meta->fetch_field()) {
$params[] = &$row[$field->name];
$this->fetch_field[] = (array) $field;
}
call_user_func_array(array($this->stmt, 'bind_result'), $params);
$result = [];
while ($this->stmt->fetch()) {
$r = [];
foreach ($row as $key => $val) {
$r[$key] = $val;
}
array_push($result, $r);
}
$this->result_fetch = $result;
}
$this->stmt->close();
if ($this->connection->errno) {
$this->debug('Unable to process MySQL query (check your params) - ' . $this->connection->error);
$this->error = $this->connection->error;
}
$this->query_count++;
} else {
$this->debug('Unable to prepare statement (check your syntax) - ' . $query);
$this->error = 'Unable to prepare statement';
}
return $this;
}
public function fetchAll() {
return $this->result_fetch;
}
public function fetchFirst() {
$result = $this->result_fetch[0];
return $result;
}
public function fetchLast() {
$jml_data = count($this->result_fetch);
$result = $this->result_fetch[$jml_data-1];
return $result;
}
public function fetchArray() {
$params = array();
$meta = $this->result_metadata;
while ($field = $meta->fetch_field()) {
$params[] = &$row[$field->name];
}
call_user_func_array(array($this->stmt, 'bind_result'), $params);
$result = array();
while ($this->stmt->fetch()) {
foreach ($row as $key => $val) {
$result[$key] = $val;
}
}
$this->stmt->close();
return $result;
}
public function fetchField()
{
return $meta->fetch_field();
}
public function numRows() {
return $this->num_rows;
}
public function close() {
return $this->connection->close();
}
public function affectedRows() {
return $this->stmt->affected_rows;
}
private function _gettype($var) {
if(is_string($var)) return 's';
if(is_float($var)) return 'd';
if(is_int($var)) return 'i';
return 'b';
}
public function escape($string)
{
return $this->connection->escape_string($string);
}
public function getError()
{
return $this->error;
}
}
?>
+416
View File
@@ -0,0 +1,416 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Page not found</title>
<style>
html {font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}
body {margin:0}
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section,
summary {display:block}
audio,
canvas,
progress,
video {display:inline-block;vertical-align:baseline}
audio:not([controls]) {display:none;height:0}
[hidden],
template {display:none}
a {background:transparent}
a:active,
a:hover {outline:0}
abbr[title] {border-bottom:1px dotted}
b,
strong {font-weight:bold}
dfn {font-style:italic}
h1 {font-size:2em;margin:0.67em 0}
mark {background:#ff0;color:#000}
small {font-size:80%}
sub,
sup {font-size:75%;line-height:0;position:relative;vertical-align:baseline}
sup {top:-0.5em}
sub {bottom:-0.25em}
img {border:0}
svg:not(:root) {overflow:hidden}
figure {margin:1em 40px}
hr {-moz-box-sizing:content-box;box-sizing:content-box;height:0}
pre {overflow:auto}
code,
kbd,
pre,
samp {font-family:monospace,monospace;font-size:1em}
button,
input,
optgroup,
select,
textarea {color:inherit;font:inherit;margin:0}
button {overflow:visible}
button,
select {text-transform:none}
button,
html input[type="button"],
input[type="reset"],
input[type="submit"] {-webkit-appearance:button;cursor:pointer}
button[disabled],
html input[disabled] {cursor:default}
button::-moz-focus-inner,
input::-moz-focus-inner {border:0;padding:0}
input {line-height:normal}
input[type="checkbox"],
input[type="radio"] {box-sizing:border-box;padding:0}
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {height:auto}
input[type="search"] {-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {-webkit-appearance:none}
fieldset {border:1px solid #c0c0c0;margin:0 2px;padding:0.35em 0.625em 0.75em}
legend {border:0;padding:0}
textarea {overflow:auto}
optgroup {font-weight:bold}
table {border-collapse:collapse;border-spacing:0;table-layout:auto;word-wrap:break-word;word-break:break-all}
td,
th {padding:0}
*,
*:before,
*:after {-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}
html {font-size:62.5%;-webkit-tap-highlight-color:rgba(0,0,0,0)}
body {font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";font-size:14px;line-height:1.42857143;color:#333;background-color:#f9f9f9}
input,
button,
select,
textarea {font-family:inherit;font-size:inherit;line-height:inherit}
button,
input,
select[multiple],
textarea {background-image:none}
a {color:#0181b9;text-decoration:none}
a:hover,
a:focus {color:#001721;text-decoration:underline}
a:focus {outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}
img {vertical-align:middle}
.img-responsive {display:block;max-width:100%;height:auto}
.img-rounded {-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}
.img-circle {border-radius:50%}
hr {margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}
.sr-only {position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);border:0}
@media print {* {text-shadow:none !important;color:#000 !important;background:transparent !important;box-shadow:none !important }a,a:visited {text-decoration:underline }a[href]:after {content:" (" attr(href) ")" }abbr[title]:after {content:" (" attr(title) ")" }a[href^="javascript:"]:after,a[href^="#"]:after {content:"" }pre,blockquote {border:1px solid #999;page-break-inside:avoid }thead {display:table-header-group }tr,img {page-break-inside:avoid }img {max-width:100% !important }p,h2,h3 {orphans:3;widows:3 }h2,h3 {page-break-after:avoid }select {background:#fff !important }.navbar {display:none }.table td,.table th {background-color:#fff !important }.btn >.caret,.dropup >.btn >.caret {border-top-color:#000 !important }.label {border:1px solid #000 }.table {border-collapse:collapse !important }.table-bordered th,.table-bordered td {border:1px solid #ddd !important }}
.container {margin-right:auto;margin-left:auto;padding-left:15px;padding-right:15px}
@media (min-width:768px) {.container {width:750px }}
@media (min-width:992px) {.container {width:970px }}
@media (min-width:1200px) {.container {width:1170px }}
.container-fluid {margin-right:auto;margin-left:auto;padding-left:15px;padding-right:15px}
.row {margin-left:-15px;margin-right:-15px}
.row-flush {margin-left:0;margin-right:0}
.row-flush [class*="col-"] {padding-left:0 !important;padding-right:0 !important}
.col-xs-1,.col-sm-1,.col-md-1,.col-lg-1,.col-xs-2,.col-sm-2,.col-md-2,.col-lg-2,.col-xs-3,.col-sm-3,.col-md-3,.col-lg-3,.col-xs-4,.col-sm-4,.col-md-4,.col-lg-4,.col-xs-5,.col-sm-5,.col-md-5,.col-lg-5,.col-xs-6,.col-sm-6,.col-md-6,.col-lg-6,.col-xs-7,.col-sm-7,.col-md-7,.col-lg-7,.col-xs-8,.col-sm-8,.col-md-8,.col-lg-8,.col-xs-9,.col-sm-9,.col-md-9,.col-lg-9,.col-xs-10,.col-sm-10,.col-md-10,.col-lg-10,.col-xs-11,.col-sm-11,.col-md-11,.col-lg-11,.col-xs-12,.col-sm-12,.col-md-12,.col-lg-12 {position:relative;min-height:1px;padding-left:15px;padding-right:15px}
.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12 {float:left}
.col-xs-12 {width:100%}
.col-xs-11 {width:91.66666667%}
.col-xs-10 {width:83.33333333%}
.col-xs-9 {width:75%}
.col-xs-8 {width:66.66666667%}
.col-xs-7 {width:58.33333333%}
.col-xs-6 {width:50%}
.col-xs-5 {width:41.66666667%}
.col-xs-4 {width:33.33333333%}
.col-xs-3 {width:25%}
.col-xs-2 {width:16.66666667%}
.col-xs-1 {width:8.33333333%}
.col-xs-pull-12 {right:100%}
.col-xs-pull-11 {right:91.66666667%}
.col-xs-pull-10 {right:83.33333333%}
.col-xs-pull-9 {right:75%}
.col-xs-pull-8 {right:66.66666667%}
.col-xs-pull-7 {right:58.33333333%}
.col-xs-pull-6 {right:50%}
.col-xs-pull-5 {right:41.66666667%}
.col-xs-pull-4 {right:33.33333333%}
.col-xs-pull-3 {right:25%}
.col-xs-pull-2 {right:16.66666667%}
.col-xs-pull-1 {right:8.33333333%}
.col-xs-pull-0 {right:0%}
.col-xs-push-12 {left:100%}
.col-xs-push-11 {left:91.66666667%}
.col-xs-push-10 {left:83.33333333%}
.col-xs-push-9 {left:75%}
.col-xs-push-8 {left:66.66666667%}
.col-xs-push-7 {left:58.33333333%}
.col-xs-push-6 {left:50%}
.col-xs-push-5 {left:41.66666667%}
.col-xs-push-4 {left:33.33333333%}
.col-xs-push-3 {left:25%}
.col-xs-push-2 {left:16.66666667%}
.col-xs-push-1 {left:8.33333333%}
.col-xs-push-0 {left:0%}
.col-xs-offset-12 {margin-left:100%}
.col-xs-offset-11 {margin-left:91.66666667%}
.col-xs-offset-10 {margin-left:83.33333333%}
.col-xs-offset-9 {margin-left:75%}
.col-xs-offset-8 {margin-left:66.66666667%}
.col-xs-offset-7 {margin-left:58.33333333%}
.col-xs-offset-6 {margin-left:50%}
.col-xs-offset-5 {margin-left:41.66666667%}
.col-xs-offset-4 {margin-left:33.33333333%}
.col-xs-offset-3 {margin-left:25%}
.col-xs-offset-2 {margin-left:16.66666667%}
.col-xs-offset-1 {margin-left:8.33333333%}
.col-xs-offset-0 {margin-left:0%}
@media (min-width:768px) {.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12 {float:left }.col-sm-12 {width:100% }.col-sm-11 {width:91.66666667% }.col-sm-10 {width:83.33333333% }.col-sm-9 {width:75% }.col-sm-8 {width:66.66666667% }.col-sm-7 {width:58.33333333% }.col-sm-6 {width:50% }.col-sm-5 {width:41.66666667% }.col-sm-4 {width:33.33333333% }.col-sm-3 {width:25% }.col-sm-2 {width:16.66666667% }.col-sm-1 {width:8.33333333% }.col-sm-pull-12 {right:100% }.col-sm-pull-11 {right:91.66666667% }.col-sm-pull-10 {right:83.33333333% }.col-sm-pull-9 {right:75% }.col-sm-pull-8 {right:66.66666667% }.col-sm-pull-7 {right:58.33333333% }.col-sm-pull-6 {right:50% }.col-sm-pull-5 {right:41.66666667% }.col-sm-pull-4 {right:33.33333333% }.col-sm-pull-3 {right:25% }.col-sm-pull-2 {right:16.66666667% }.col-sm-pull-1 {right:8.33333333% }.col-sm-pull-0 {right:0% }.col-sm-push-12 {left:100% }.col-sm-push-11 {left:91.66666667% }.col-sm-push-10 {left:83.33333333% }.col-sm-push-9 {left:75% }.col-sm-push-8 {left:66.66666667% }.col-sm-push-7 {left:58.33333333% }.col-sm-push-6 {left:50% }.col-sm-push-5 {left:41.66666667% }.col-sm-push-4 {left:33.33333333% }.col-sm-push-3 {left:25% }.col-sm-push-2 {left:16.66666667% }.col-sm-push-1 {left:8.33333333% }.col-sm-push-0 {left:0% }.col-sm-offset-12 {margin-left:100% }.col-sm-offset-11 {margin-left:91.66666667% }.col-sm-offset-10 {margin-left:83.33333333% }.col-sm-offset-9 {margin-left:75% }.col-sm-offset-8 {margin-left:66.66666667% }.col-sm-offset-7 {margin-left:58.33333333% }.col-sm-offset-6 {margin-left:50% }.col-sm-offset-5 {margin-left:41.66666667% }.col-sm-offset-4 {margin-left:33.33333333% }.col-sm-offset-3 {margin-left:25% }.col-sm-offset-2 {margin-left:16.66666667% }.col-sm-offset-1 {margin-left:8.33333333% }.col-sm-offset-0 {margin-left:0% }}
@media (min-width:992px) {.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12 {float:left }.col-md-12 {width:100% }.col-md-11 {width:91.66666667% }.col-md-10 {width:83.33333333% }.col-md-9 {width:75% }.col-md-8 {width:66.66666667% }.col-md-7 {width:58.33333333% }.col-md-6 {width:50% }.col-md-5 {width:41.66666667% }.col-md-4 {width:33.33333333% }.col-md-3 {width:25% }.col-md-2 {width:16.66666667% }.col-md-1 {width:8.33333333% }.col-md-pull-12 {right:100% }.col-md-pull-11 {right:91.66666667% }.col-md-pull-10 {right:83.33333333% }.col-md-pull-9 {right:75% }.col-md-pull-8 {right:66.66666667% }.col-md-pull-7 {right:58.33333333% }.col-md-pull-6 {right:50% }.col-md-pull-5 {right:41.66666667% }.col-md-pull-4 {right:33.33333333% }.col-md-pull-3 {right:25% }.col-md-pull-2 {right:16.66666667% }.col-md-pull-1 {right:8.33333333% }.col-md-pull-0 {right:0% }.col-md-push-12 {left:100% }.col-md-push-11 {left:91.66666667% }.col-md-push-10 {left:83.33333333% }.col-md-push-9 {left:75% }.col-md-push-8 {left:66.66666667% }.col-md-push-7 {left:58.33333333% }.col-md-push-6 {left:50% }.col-md-push-5 {left:41.66666667% }.col-md-push-4 {left:33.33333333% }.col-md-push-3 {left:25% }.col-md-push-2 {left:16.66666667% }.col-md-push-1 {left:8.33333333% }.col-md-push-0 {left:0% }.col-md-offset-12 {margin-left:100% }.col-md-offset-11 {margin-left:91.66666667% }.col-md-offset-10 {margin-left:83.33333333% }.col-md-offset-9 {margin-left:75% }.col-md-offset-8 {margin-left:66.66666667% }.col-md-offset-7 {margin-left:58.33333333% }.col-md-offset-6 {margin-left:50% }.col-md-offset-5 {margin-left:41.66666667% }.col-md-offset-4 {margin-left:33.33333333% }.col-md-offset-3 {margin-left:25% }.col-md-offset-2 {margin-left:16.66666667% }.col-md-offset-1 {margin-left:8.33333333% }.col-md-offset-0 {margin-left:0% }}
@media (min-width:1200px) {.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12 {float:left }.col-lg-12 {width:100% }.col-lg-11 {width:91.66666667% }.col-lg-10 {width:83.33333333% }.col-lg-9 {width:75% }.col-lg-8 {width:66.66666667% }.col-lg-7 {width:58.33333333% }.col-lg-6 {width:50% }.col-lg-5 {width:41.66666667% }.col-lg-4 {width:33.33333333% }.col-lg-3 {width:25% }.col-lg-2 {width:16.66666667% }.col-lg-1 {width:8.33333333% }.col-lg-pull-12 {right:100% }.col-lg-pull-11 {right:91.66666667% }.col-lg-pull-10 {right:83.33333333% }.col-lg-pull-9 {right:75% }.col-lg-pull-8 {right:66.66666667% }.col-lg-pull-7 {right:58.33333333% }.col-lg-pull-6 {right:50% }.col-lg-pull-5 {right:41.66666667% }.col-lg-pull-4 {right:33.33333333% }.col-lg-pull-3 {right:25% }.col-lg-pull-2 {right:16.66666667% }.col-lg-pull-1 {right:8.33333333% }.col-lg-pull-0 {right:0% }.col-lg-push-12 {left:100% }.col-lg-push-11 {left:91.66666667% }.col-lg-push-10 {left:83.33333333% }.col-lg-push-9 {left:75% }.col-lg-push-8 {left:66.66666667% }.col-lg-push-7 {left:58.33333333% }.col-lg-push-6 {left:50% }.col-lg-push-5 {left:41.66666667% }.col-lg-push-4 {left:33.33333333% }.col-lg-push-3 {left:25% }.col-lg-push-2 {left:16.66666667% }.col-lg-push-1 {left:8.33333333% }.col-lg-push-0 {left:0% }.col-lg-offset-12 {margin-left:100% }.col-lg-offset-11 {margin-left:91.66666667% }.col-lg-offset-10 {margin-left:83.33333333% }.col-lg-offset-9 {margin-left:75% }.col-lg-offset-8 {margin-left:66.66666667% }.col-lg-offset-7 {margin-left:58.33333333% }.col-lg-offset-6 {margin-left:50% }.col-lg-offset-5 {margin-left:41.66666667% }.col-lg-offset-4 {margin-left:33.33333333% }.col-lg-offset-3 {margin-left:25% }.col-lg-offset-2 {margin-left:16.66666667% }.col-lg-offset-1 {margin-left:8.33333333% }.col-lg-offset-0 {margin-left:0% }}
.clearfix:before,
.clearfix:after,
.container:before,
.container:after,
.container-fluid:before,
.container-fluid:after,
.row:before,
.row:after {content:" ";display:table}
.clearfix:after,
.container:after,
.container-fluid:after,
.row:after {clear:both}
.center-block {display:block;margin-left:auto;margin-right:auto}
.pull-right {float:right !important}
.pull-left {float:left !important}
.hide {display:none !important}
.show {display:block !important}
.invisible {visibility:hidden}
.text-hide {font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}
.hidden {display:none !important;visibility:hidden !important}
.affix {position:fixed}
@-ms-viewport {width:device-width}
.visible-xs,
.visible-sm,
.visible-md,
.visible-lg {display:none !important}
@media (max-width:767px) {.visible-xs {display:block !important }table.visible-xs {display:table }tr.visible-xs {display:table-row !important }th.visible-xs,td.visible-xs {display:table-cell !important }}
@media (min-width:768px) and (max-width:991px) {.visible-sm {display:block !important }table.visible-sm {display:table }tr.visible-sm {display:table-row !important }th.visible-sm,td.visible-sm {display:table-cell !important }}
@media (min-width:992px) and (max-width:1199px) {.visible-md {display:block !important }table.visible-md {display:table }tr.visible-md {display:table-row !important }th.visible-md,td.visible-md {display:table-cell !important }}
@media (min-width:1200px) {.visible-lg {display:block !important }table.visible-lg {display:table }tr.visible-lg {display:table-row !important }th.visible-lg,td.visible-lg {display:table-cell !important }}
@media (max-width:767px) {.hidden-xs {display:none !important }}
@media (min-width:768px) and (max-width:991px) {.hidden-sm {display:none !important }}
@media (min-width:992px) and (max-width:1199px) {.hidden-md {display:none !important }}
@media (min-width:1200px) {.hidden-lg {display:none !important }}
.visible-print {display:none !important}
@media print {.visible-print {display:block !important }table.visible-print {display:table }tr.visible-print {display:table-row !important }th.visible-print,td.visible-print {display:table-cell !important }}
@media print {.hidden-print {display:none !important }}
h1,
h2,
h3,
h4,
h5,
h6,
.h1,
.h2,
.h3,
.h4,
.h5,
.h6 {font-family:inherit;font-weight:400;line-height:1.1;color:inherit}
h1 small,
h2 small,
h3 small,
h4 small,
h5 small,
h6 small,
.h1 small,
.h2 small,
.h3 small,
.h4 small,
.h5 small,
.h6 small,
h1 .small,
h2 .small,
h3 .small,
h4 .small,
h5 .small,
h6 .small,
.h1 .small,
.h2 .small,
.h3 .small,
.h4 .small,
.h5 .small,
.h6 .small {font-weight:normal;line-height:1;color:#999}
h1,
.h1,
h2,
.h2,
h3,
.h3 {margin-top:20px;margin-bottom:10px}
h1 small,
.h1 small,
h2 small,
.h2 small,
h3 small,
.h3 small,
h1 .small,
.h1 .small,
h2 .small,
.h2 .small,
h3 .small,
.h3 .small {font-size:65%}
h4,
.h4,
h5,
.h5,
h6,
.h6 {margin-top:10px;margin-bottom:10px}
h4 small,
.h4 small,
h5 small,
.h5 small,
h6 small,
.h6 small,
h4 .small,
.h4 .small,
h5 .small,
.h5 .small,
h6 .small,
.h6 .small {font-size:75%}
h1,
.h1 {font-size:36px}
h2,
.h2 {font-size:30px}
h3,
.h3 {font-size:24px}
h4,
.h4 {font-size:18px}
h5,
.h5 {font-size:14px}
h6,
.h6 {font-size:12px}
p {margin:0 0 10px}
.lead {margin-bottom:20px;font-size:16px;font-weight:200;line-height:1.4}
@media (min-width:768px) {.lead {font-size:21px }}
small,
.small {font-size:85%}
cite {font-style:normal}
.text-left {text-align:left}
.text-right {text-align:right}
.text-center {text-align:center}
.text-justify {text-align:justify}
.text-muted {color:#999}
.text-primary {color:#34495e}
a.text-primary:hover {color:#222f3d}
.text-success {color:#3c763d}
a.text-success:hover {color:#2b542c}
.text-info {color:#31708f}
a.text-info:hover {color:#245269}
.text-warning {color:#8a6d3b}
a.text-warning:hover {color:#66512c}
.text-danger {color:#a94442}
a.text-danger:hover {color:#843534}
.bg-primary {color:#fff;background-color:#34495e}
a.bg-primary:hover {background-color:#222f3d}
.bg-success {background-color:#dff0d8}
a.bg-success:hover {background-color:#c1e2b3}
.bg-info {background-color:#d9edf7}
a.bg-info:hover {background-color:#afd9ee}
.bg-warning {background-color:#fcf8e3}
a.bg-warning:hover {background-color:#f7ecb5}
.bg-danger {background-color:#f2dede}
a.bg-danger:hover {background-color:#e4b9b9}
.page-header {padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}
ul,
ol {margin-top:0;margin-bottom:10px}
ul ul,
ol ul,
ul ol,
ol ol {margin-bottom:0}
.list-unstyled {padding-left:0;list-style:none}
.list-inline {padding-left:0;list-style:none;margin-left:-5px}
.list-inline >li {display:inline-block;padding-left:5px;padding-right:5px}
dl {margin-top:0;margin-bottom:20px}
dt,
dd {line-height:1.42857143}
dt {font-weight:bold}
dd {margin-left:0}
@media (min-width:768px) {.dl-horizontal dt {float:left;width:160px;clear:left;text-align:right;overflow:hidden;text-overflow:ellipsis;white-space:nowrap }.dl-horizontal dd {margin-left:180px }}
abbr[title],
abbr[data-original-title] {cursor:help;border-bottom:1px dotted #999}
.initialism {font-size:90%;text-transform:uppercase}
blockquote {padding:10px 20px;margin:0 0 20px;font-size:17.5px;border-left:5px solid #eee}
blockquote p:last-child,
blockquote ul:last-child,
blockquote ol:last-child {margin-bottom:0}
blockquote footer,
blockquote small,
blockquote .small {display:block;font-size:80%;line-height:1.42857143;color:#999}
blockquote footer:before,
blockquote small:before,
blockquote .small:before {content:'\2014 \00A0'}
.blockquote-reverse,
blockquote.pull-right {padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0;text-align:right}
.blockquote-reverse footer:before,
blockquote.pull-right footer:before,
.blockquote-reverse small:before,
blockquote.pull-right small:before,
.blockquote-reverse .small:before,
blockquote.pull-right .small:before {content:''}
.blockquote-reverse footer:after,
blockquote.pull-right footer:after,
.blockquote-reverse small:after,
blockquote.pull-right small:after,
.blockquote-reverse .small:after,
blockquote.pull-right .small:after {content:'\00A0 \2014'}
blockquote:before,
blockquote:after {content:""}
address {margin-bottom:20px;font-style:normal;line-height:1.42857143}
.oc-icon-chain:before,
.icon-chain:before,
.oc-icon-chain-broken:before,
.icon-chain-broken:before {content:"\f127"}
.close {float:right;font-size:21px;font-weight:bold;line-height:1;color:#000;text-shadow:0 1px 0 #fff;font-family:sans-serif;opacity:0.2;filter:alpha(opacity=20)}
.close:hover,
.close:focus {color:#000;text-decoration:none;cursor:pointer;opacity:0.5;filter:alpha(opacity=50)}
button.close {padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}
@font-face {font-family:'FontAwesome';src:url('../library/font-awesome-4.7.0/fonts/fontawesome-webfont.eot?v=1.0.1');src:url('../library/font-awesome-4.7.0/fonts/fontawesome-webfont.eot?#iefix&v=1.0.1') format('embedded-opentype'),url('../library/font-awesome-4.7.0/fonts/fontawesome-webfont.woff?v=1.0.1') format('woff'),url('../ui/font/fontawesome-webfont.ttf?v=1.0.1') format('truetype'),url('../library/font-awesome-4.7.0/fonts/fontawesome-webfont.svg#fontawesomeregular?v=1.0.1') format('svg');font-weight:normal;font-style:normal}
[class^="icon-"],
[class*=" icon-"] {font-family:FontAwesome;font-weight:normal;font-style:normal;text-decoration:inherit;-webkit-font-smoothing:antialiased;*margin-right:.3em;display:inline;width:auto;height:auto;line-height:normal;vertical-align:baseline;background-image:none;background-position:0% 0%;background-repeat:repeat;margin-top:0}
[class^="icon-"]:before,
[class*=" icon-"]:before {text-decoration:inherit;display:inline-block;speak:none}
[class^="icon-"].pull-left,
[class*=" icon-"].pull-left {margin-right:.3em}
[class^="icon-"].pull-right,
[class*=" icon-"].pull-right {margin-left:.3em}
[class^="oc-icon-"]:before,
[class*=" oc-icon-"]:before {display:inline-block;margin-right:8px;font-family:FontAwesome;font-weight:normal;font-style:normal;text-decoration:inherit;-webkit-font-smoothing:antialiased;*margin-right:.3em;vertical-align:baseline}
[class^="oc-icon-"].empty:before,
[class*=" oc-icon-"].empty:before {margin-right:0}
.icon-lg {font-size:1.33333333em;line-height:0.75em;vertical-align:-15%}
.icon-2x {font-size:2em}
.icon-3x {font-size:3em}
.icon-4x {font-size:4em}
.icon-5x {font-size:5em}
body {padding-top:20px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";background:#f3f3f3;color:#405261}
h1,
h2,
h3,
h4,
h5 {font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";text-transform:uppercase}
h1 {font-weight:300;font-size:50px;margin-bottom:15px}
h1 i[class^="icon-"]:before {font-size:46px}
i[class^="icon-"].warning {color:#c84530}
h3 {font-size:24px;font-weight:300}
p.lead {font-size:16px;font-weight:300}
</style>
</head>
<body>
<div class="container">
<h1><i class="icon-chain-broken warning"></i> Page not found</h1>
<p class="lead">The requested page cannot be found.</p>
</div>
</body>
</html>
+1318
View File
File diff suppressed because it is too large Load Diff
+224
View File
@@ -0,0 +1,224 @@
<?php
class Pagination {
var $php_self;
var $rows_per_page = 10; //Number of records to display per page
var $total_rows = 0; //Total number of rows returned by the query
var $links_per_page = 5; //Number of links to display per page
var $append = ""; //Paremeters to append to pagination links
var $sql = "";
var $debug = false;
var $conn = false;
var $page = 1;
var $max_pages = 0;
var $offset = 0;
var $jen;
/**
* Constructor
*
* @param resource $connection Mysql connection link
* @param string $sql SQL query to paginate. Example : SELECT * FROM users
* @param integer $rows_per_page Number of records to display per page. Defaults to 10
* @param integer $links_per_page Number of links to display per page. Defaults to 5
* @param string $append Parameters to be appended to pagination links
*/
function __construct($connection, $sql, $rows_per_page = 10, $links_per_page = 5, $append = "", $current_page) {
$this->conn = $connection;
$this->sql = $sql;
$this->rows_per_page = (int)$rows_per_page;
if(intval($links_per_page) > 0) {
$this->links_per_page = (int)$links_per_page;
}
else {
$this->links_per_page = 5;
}
$this->append = $append;
$this->php_self = $current_page . $append ."&";
if(isset($_GET['page'])) {
$this->page = intval($_GET['page']);
}
}
/**
* Executes the SQL query and initializes internal variables
*
* @access public
* @return resource
*/
function paginate() {
global $logger;
//Check for valid mysql connection
if(!$this->conn || !is_object($this->conn)) {
if($this->debug) $logger->addInfo("Connection missing");
return false;
}
//Find total number of rows
$all_rs = $this->conn->query($this->sql);
if(!$all_rs) {
if($this->debug) $logger->addInfo("SQL query failed. Check your query.<br /><br />Error Returned: ".$this->conn->error);
return false;
}
$this->total_rows = $all_rs->numRows();
// $this->conn->close();
//Max number of pages
$this->max_pages = ceil($this->total_rows/$this->rows_per_page);
if($this->links_per_page > $this->max_pages) {
$this->links_per_page = $this->max_pages;
}
//Check the page value just in case someone is trying to input an aribitrary value
if($this->page > $this->max_pages || $this->page <= 0) {
$this->page = 1;
}
//Calculate Offset
$this->offset = $this->rows_per_page * ($this->page-1);
//Fetch the required result set
if(_DBTYPE_ == 'mysqli') {
$this->sql .= " LIMIT {$this->offset}, {$this->rows_per_page}";
}
elseif(_DBTYPE_ == 'postgre') {
$this->sql .= " LIMIT {$this->rows_per_page} OFFSET {$this->offset}";
}
$rs = $this->conn->query($this->sql);
if(!$rs) {
if($this->debug) $logger->addInfo("Pagination query failed. Check your query.<br /><br />Error Returned: ".$this->conn->error);
return false;
}
return $rs;
}
/**
* Display the link to the first page
*
* @access public
* @param string $tag Text string to be displayed as the link. Defaults to 'First'
* @return string
*/
function renderFirst($tag='Awal') {
if($this->page == 1) {
return '<a class="page-link" href="#">'.$tag.'</a>';
}
else {
return '<a class="page-link" href="'.$this->php_self.'page=1">'.$tag.'</a>';
}
}
/**
* Display the link to the last page
*
* @access public
* @param string $tag Text string to be displayed as the link. Defaults to 'Last'
* @return string
*/
function renderLast($tag='Akhir') {
if($this->page == $this->max_pages) {
return '<a class="page-link" href="#">'.$tag.'</a>';
}
else {
return '<a class="page-link" href="'.$this->php_self.'page='.$this->max_pages.'">'.$tag.'</a>';
}
}
/**
* Display the next link
*
* @access public
* @param string $tag Text string to be displayed as the link. Defaults to '>>'
* @return string
*/
function renderNext($tag=' Lanjut ') {
if($this->page < $this->max_pages) {
return '<a class="page-link" href="'.$this->php_self.'page='.($this->page+1).'">'.$tag.'</a>';
}
else {
return '<a class="page-link" href="#">'.$tag.'</a>';
}
}
/**
* Display the previous link
*
* @access public
* @param string $tag Text string to be displayed as the link. Defaults to '<<'
* @return string
*/
function renderPrev($tag=' Kembali ') {
if($this->page > 1) {
return '<a class="page-link" href="'.$this->php_self.'page='.($this->page-1).'">'.$tag.'</a>';
}
else {
return '<a class="page-link" href="#">'.$tag.'</a>';
}
}
/**
* Display the page links
*
* @access public
* @return string
*/
function renderNav() {
$batch = @ceil($this->page/$this->links_per_page);
$end = $batch * $this->links_per_page;
if($end == $this->page) {
//$end = $end + $this->links_per_page - 1;
//$end = $end + ceil($this->links_per_page/2);
}
if($end > $this->max_pages) {
$end = $this->max_pages;
}
$start = $end - $this->links_per_page + 1;
$links = '';
for( $i=$start ; $i <= $end ; $i++) {
if($i == $this->page) {
$links .= '<li class="page-item active"> <a class="page-link" href="'.$this->php_self.'page='.$i.'">'.$i.'</a> </li>';
}
else {
$links .= '<li class="page-item"> <a class="page-link" href="'.$this->php_self.'page='.$i.'">'.$i.'</a> </li>';
}
}
return $links;
}
/**
* Display full pagination navigation
*
* @access public
* @return string
*/
function renderFullNav() {
return '<nav aria-label="Page navigation">
<ul class="pagination justify-content-center">
<li class="page-item">'.$this->renderFirst().'</li>
<li class="page-item">'.$this->renderPrev().'</li>
'.$this->renderNav().'
<li class="page-item">'.$this->renderNext().'</li>
<li class="page-item">'.$this->renderLast().'</li>
</ul>
</nav>';
}
/**
* Set debug mode
*
* @access public
* @param bool $debug Set to TRUE to enable debug messages
* @return void
*/
function setDebug($debug) {
$this->debug = $debug;
}
}
?>
+225
View File
@@ -0,0 +1,225 @@
<?php
class Pagination_big {
var $php_self;
var $rows_per_page = 10; //Number of records to display per page
var $total_rows = 0; //Total number of rows returned by the query
var $links_per_page = 5; //Number of links to display per page
var $append = ""; //Paremeters to append to pagination links
var $sql = "";
var $debug = false;
var $conn = false;
var $page = 1;
var $max_pages = 0;
var $offset = 0;
var $jen;
/**
* Constructor
*
* @param resource $connection Mysql connection link
* @param string $sql SQL query to paginate. Example : SELECT * FROM users
* @param integer $rows_per_page Number of records to display per page. Defaults to 10
* @param integer $links_per_page Number of links to display per page. Defaults to 5
* @param string $append Parameters to be appended to pagination links
*/
function __construct($connection, $sql, $sqlcounter, $rows_per_page = 10, $links_per_page = 5, $append = "") {
$this->conn = $connection;
$this->sql = $sql;
$this->sqlcounter = $sqlcounter;
$this->rows_per_page = (int)$rows_per_page;
if(intval($links_per_page) > 0) {
$this->links_per_page = (int)$links_per_page;
}
else {
$this->links_per_page = 5;
}
$this->append = $append;
$this->jen = (array_key_exists('jen', $_GET)) ? $_GET['jen'] : null;
$this->php_self = $_SERVER['PHP_SELF']."?link=".$_REQUEST['link']."&";
if(isset($_GET['page'])) {
$this->page = intval($_GET['page']);
}
}
/**
* Executes the SQL query and initializes internal variables
*
* @access public
* @return resource
*/
function paginate() {
global $logger;
//Check for valid mysql connection
if(!$this->conn || !is_object($this->conn)) {
if($this->debug) $logger->addInfo("Connection missing");
return false;
}
//Find total number of rows
$all_rs = $this->conn->query($this->sqlcounter);
if(!$all_rs) {
if($this->debug) $logger->addInfo("SQL query failed. Check your query.<br /><br />Error Returned: ".$this->conn->error);
return false;
}
$this->total_rows = $all_rs->fetchAll()[0]['counter'];
// $this->conn->close();
//Max number of pages
$this->max_pages = ceil($this->total_rows/$this->rows_per_page);
if($this->links_per_page > $this->max_pages) {
$this->links_per_page = $this->max_pages;
}
//Check the page value just in case someone is trying to input an aribitrary value
if($this->page > $this->max_pages || $this->page <= 0) {
$this->page = 1;
}
//Calculate Offset
$this->offset = $this->rows_per_page * ($this->page-1);
//Fetch the required result set
if(_DBTYPE_ == 'mysqli') {
$this->sql .= " LIMIT {$this->offset}, {$this->rows_per_page}";
}
elseif(_DBTYPE_ == 'postgre') {
$this->sql .= " LIMIT {$this->rows_per_page} OFFSET {$this->offset}";
}
$rs = $this->conn->query($this->sql);
if(!$rs) {
if($this->debug) $logger->addInfo("Pagination query failed. Check your query.<br /><br />Error Returned: ".$this->conn->error);
return false;
}
return $rs;
}
/**
* Display the link to the first page
*
* @access public
* @param string $tag Text string to be displayed as the link. Defaults to 'First'
* @return string
*/
function renderFirst($tag='Awal') {
if($this->page == 1) {
return '<a class="page-link" href="#">'.$tag.'</a>';
}
else {
return '<a class="page-link" href="'.$this->php_self.'page=1">'.$tag.'</a>';
}
}
/**
* Display the link to the last page
*
* @access public
* @param string $tag Text string to be displayed as the link. Defaults to 'Last'
* @return string
*/
function renderLast($tag='Akhir') {
if($this->page == $this->max_pages) {
return '<a class="page-link" href="#">'.$tag.'</a>';
}
else {
return '<a class="page-link" href="'.$this->php_self.'page='.$this->max_pages.'">'.$tag.'</a>';
}
}
/**
* Display the next link
*
* @access public
* @param string $tag Text string to be displayed as the link. Defaults to '>>'
* @return string
*/
function renderNext($tag=' Lanjut ') {
if($this->page < $this->max_pages) {
return '<a class="page-link" href="'.$this->php_self.'page='.($this->page+1).'">'.$tag.'</a>';
}
else {
return '<a class="page-link" href="#">'.$tag.'</a>';
}
}
/**
* Display the previous link
*
* @access public
* @param string $tag Text string to be displayed as the link. Defaults to '<<'
* @return string
*/
function renderPrev($tag=' Kembali ') {
if($this->page > 1) {
return '<a class="page-link" href="'.$this->php_self.'page='.($this->page-1).'">'.$tag.'</a>';
}
else {
return '<a class="page-link" href="#">'.$tag.'</a>';
}
}
/**
* Display the page links
*
* @access public
* @return string
*/
function renderNav() {
$batch = @ceil($this->page/$this->links_per_page);
$end = $batch * $this->links_per_page;
if($end == $this->page) {
//$end = $end + $this->links_per_page - 1;
//$end = $end + ceil($this->links_per_page/2);
}
if($end > $this->max_pages) {
$end = $this->max_pages;
}
$start = $end - $this->links_per_page + 1;
$links = '';
for( $i=$start ; $i <= $end ; $i++) {
if($i == $this->page) {
$links .= '<li class="page-item active"> <a class="page-link" href="'.$this->php_self.'page='.$i.'">'.$i.'</a> </li>';
}
else {
$links .= '<li class="page-item"> <a class="page-link" href="'.$this->php_self.'page='.$i.'">'.$i.'</a> </li>';
}
}
return $links;
}
/**
* Display full pagination navigation
*
* @access public
* @return string
*/
function renderFullNav() {
return '<nav aria-label="Page navigation">
<ul class="pagination justify-content-center">
<li class="page-item">'.$this->renderFirst().'</li>
<li class="page-item">'.$this->renderPrev().'</li>
'.$this->renderNav().'
<li class="page-item">'.$this->renderNext().'</li>
<li class="page-item">'.$this->renderLast().'</li>
</ul>
</nav>';
}
/**
* Set debug mode
*
* @access public
* @param bool $debug Set to TRUE to enable debug messages
* @return void
*/
function setDebug($debug) {
$this->debug = $debug;
}
}
?>
+38
View File
@@ -0,0 +1,38 @@
<?php
class PEC {
protected $connection = null;
public function connect() {
// we don't need to connect twice
if ( $this->connection ) {
return;
}
// data for making connection
$mssql_server = $_ENV['PEC_DB_HOST'];
$mssql_data = array("UID" => $_ENV['PEC_DB_USER'],
"PWD" => $_ENV['PEC_DB_PASS'],
"Database" => $_ENV['PEC_DB_NAME']);
// try to connect
$this->connection = sqlsrv_connect($mssql_server, $mssql_data);
if(! $this->connection){
return 'Failed to connect to host';
}
}
public function getData ($query) {
// reset results; is this really needed as object's variable? Can't it be just local function's variable??
$this->data_array = array();
$result = $this->query($query);
while ($row = sqlsrv_fetch_array($result)) {
$this->data_array[] = $row;
}
return $this->data_array;
}
public function query($query) {
$result = sqlsrv_query($this->connection, $query) or die("This Query didn't work.. [QUERY = ".$query."]");
return $result;
}
}
+908
View File
@@ -0,0 +1,908 @@
<?php
if (!session_id()) {
session_start();
}
require_once 'main.php';
require_once('SQLServerDb.php');
$db_pec = new SQLServerDb(
$_ENV['PEC_DB_USER'],
$_ENV['PEC_DB_PASS'],
$_ENV['PEC_DB_NAME'],
$_ENV['PEC_DB_HOST']
);
$post = $_REQUEST;
if (array_key_exists('list_pec', $post) && $post['list_pec'] == true) {
global $db_pec;
global $db;
$tgl = (array_key_exists('tgl_awal', $post)) ? $post['tgl_awal'] : null;
$jam_awal = (array_key_exists('jam_awal', $post)) ? $post['jam_awal'] : null;
$jam_akhir = (array_key_exists('jam_akhir', $post)) ? $post['jam_akhir'] : null;
$nomr = (array_key_exists('nomr', $post)) ? $post['nomr'] : null;
$nobill = (array_key_exists('nobill', $post)) ? $post['nobill'] : null;
$ruang = (array_key_exists('ruang', $post)) ? $post['ruang'] : null;
$where_nomr = ($nomr != null) ? ' and p.Lab_PatientID = \'' . $nomr . '\'' : null;
$where_tgl_list = ($tgl != null) ? " and convert(date,r.TestEndDate) = '$tgl' " : '';
$where_ruang = ($ruang != null) ? " and p.Location like '%$ruang' " : '';
$where_jam = ($jam_awal != null && $jam_akhir != null) ? " and convert(time,TestEndDate) between '$jam_awal' and '$jam_akhir' " : '';
$tmp_list_trans = $db_pec->get_results("SELECT p.ID as p_id,p.Lab_PatientID as nomr,p.Location as ruang,r.ID as r_id,r.UnivTestName as DN,r.RValue as rvalue,r.Unit as unit,r.ANormalFlag as normalflah,convert(varchar, r.TestEndDate, 20) as specimen_dttm,op.FirstName,op.LastName
from Patient as p
left join Result as r on p.ID = r._PID
left join Operator as op on r.OperatiorID = op.OperatorID
where r.RValue <> '' $where_tgl_list $where_nomr $where_ruang $where_jam
order by r.TestEndDate desc", 'array');
if (!empty($tmp_list_trans)) {
// get list t_poct berdasarkan tanggl
$where_cek_poct = ($tgl != null) ? "and substring(date_trunc('day',tgl_spesimen::timestamp)::varchar from 1 for 10) = '$tgl'" : '';
$tmp_poct = $db->query("SELECT p_id,r_id from t_poct where st_aktif = 1 $where_cek_poct ");
$arr_poct_validated = [];
if ($tmp_poct->numRows() > 0) {
foreach ($tmp_poct->fetchAll() as $row) {
$arr_poct_validated[] = $row['p_id'] . '|' . $row['r_id'];
}
}
$arr_pasien = [];
$arr_tempat = ['' => 'Semua Ruang'];
$no = 1;
foreach ($tmp_list_trans as $k => $list) {
// get nobill
list($ruang, $nama_ruang) = explode('^', $list['ruang']);
$arr_tempat[$nama_ruang] = $nama_ruang;
if (preg_match("/IRD|IGD/", $nama_ruang)) {
$get_nobill = $db->query("SELECT nobill from t_billrajal where nomr = '{$list['nomr']}' order by idxbill desc limit 1");
} else {
$get_nobill = $db->query("SELECT nobill from t_billranap where nomr = '{$list['nomr']}' order by idxbill desc limit 1");
}
$get_nobill = ($get_nobill->numRows() > 0) ? $get_nobill->fetchFirst()['nobill'] : '';
// lewati jika sudah tersimpan di tabel t_poct
if (
in_array($list['p_id'] . '|' . $list['r_id'], $arr_poct_validated) == true
|| ($nobill != '' && $get_nobill != $nobill)
) {
continue;
}
unset($tmp_list_trans[$k][0]);
unset($tmp_list_trans[$k][1]);
unset($tmp_list_trans[$k][2]);
unset($tmp_list_trans[$k][3]);
unset($tmp_list_trans[$k][4]);
unset($tmp_list_trans[$k][5]);
unset($tmp_list_trans[$k][6]);
unset($tmp_list_trans[$k][7]);
unset($tmp_list_trans[$k][8]);
unset($list[0]);
unset($list[1]);
unset($list[2]);
unset($list[3]);
unset($list[4]);
unset($list[5]);
unset($list[6]);
unset($list[7]);
unset($list[8]);
$arr_pasien[$k] = $list;
// get pasien
$tmp_pasien = $db->query("SELECT nama,tgllahir from m_pasien where nomr = '{$list['nomr']}'");
if ($tmp_pasien->numRows() > 0) {
$dt_pasien = $tmp_pasien->fetchFirst();
$arr_pasien[$k]['nama_pasien'] = $dt_pasien['nama'];
$arr_pasien[$k]['tgllahir'] = $dt_pasien['tgllahir'];
} else {
$arr_pasien[$k]['nama_pasien'] = '';
$arr_pasien[$k]['tgllahir'] = '';
}
$arr_pasien[$k]['no'] = $no;
$arr_pasien[$k]['nobill'] = $get_nobill;
$no++;
}
$form_filter_ruang = form_dropdown("ruang", $arr_tempat, '', 'class="form-control"');
echo json_encode(['pasien' => $arr_pasien, 'ruang' => $form_filter_ruang]);
} else {
echo json_encode(['error' => true, 'msg' => 'Data tidak ditemukan']);
}
exit;
} elseif (array_key_exists('validasi', $post) && $post['validasi'] == true) {
$form_data = $post['input'];
$ip = getRealIpAddr();
$arr_data = [];
foreach ($form_data as $input) {
if ($input['nobill'] != '') {
$arr_data[] = $input;
}
}
if (!empty($arr_data)) {
$arr_error = [];
foreach ($arr_data as $row) {
$arr_insert = $row;
$arr_insert['p_id'] = ['value' => $row['p_id'], 'type' => 'number'];
$arr_insert['r_id'] = ['value' => $row['r_id'], 'type' => 'number'];
$arr_insert['nobill'] = ['value' => $row['nobill'], 'type' => 'number'];
$arr_insert['st_aktif'] = ['value' => 1, 'type' => 'number'];
$arr_insert['petugas'] = $_SESSION['NIP'];
$arr_insert['tgl_entri'] = date('Y-m-d H:i:s');
$cek_nobill = $db->query("SELECT distinct nobill,brn.nomr,0 as st_rajal,r.no as kd_tl, r.idx_ruang,brn.idxdaftar,brn.carabayar from t_billranap brn
join t_admission a on brn.idxdaftar = a.id_admission
join m_ruang r on brn.kdpoly = a.noruang
where nobill = {$row['nobill']}
UNION
SELECT distinct nobill,brj.nomr,1 as st_rajal,r.no as kd_tl,r.idx_ruang,brj.idxdaftar,brj.carabayar from t_billrajal brj
join t_pendaftaran p on brj.idxdaftar = p.idxdaftar and brj.nomr = p.nomr
join m_ruang r on brj.kdpoly = p.kdpoly
where nobill = {$row['nobill']}");
if ($cek_nobill->numRows() > 0) {
$dt_bill = $cek_nobill->fetchFirst();
if (preg_match("/glu/i", $row['jenis_pemeriksaan'])) {
$kode_tindakan = 'R.LPK.113';
} else {
$kode_tindakan = 'R.LPK.113';
}
$query = "INSERT into t_poct " . bind_sql($arr_insert);
$save_poct = execute($query);
if ($save_poct) {
$get_tarif = getTarif($kode_tindakan);
$jasa_sarana = ($get_tarif['jasa_sarana'] != '') ? $get_tarif['jasa_sarana'] : 0;
$jasa_pelayanan = ($get_tarif['jasa_pelayanan'] != '') ? $get_tarif['jasa_pelayanan'] : 0;
$jasa_anastesi = ($get_tarif['jasa_anastesi'] != '') ? $get_tarif['jasa_anastesi'] : 0;
// tambah billing
$save = "INSERT into tmp_cartbayar " . bind_sql([
'kodetarif' => $kode_tindakan,
'ip' => $ip,
'qty' => ['value' => 1, 'type' => 'number'],
'poly' => ['value' => $dt_bill['kd_tl'], 'type' => 'number'],
'unit' => ['value' => $_SESSION['KDUNIT'], 'type' => 'number'],
'tarif' => ['value' => $get_tarif['jumlah'], 'type' => 'number'],
'discount' => ['value' => 0, 'type' => 'number'],
'tottarif' => ['value' => $get_tarif['jumlah'], 'type' => 'number'],
'jasa_sarana' => ['value' => $jasa_sarana, 'type' => 'number'],
'jasa_pelayanan' => ['value' => $jasa_pelayanan, 'type' => 'number'],
'jasa_anastesi' => ['value' => $jasa_anastesi, 'type' => 'number'],
'kddokter' => ['value' => 'null', 'type' => 'number']
]);
$result_tmp = execute($save . " RETURNING idxbayar");
$idxbayar = $result_tmp->fetchFirst()['idxbayar'];
if ($dt_bill['st_rajal'] == 1) {
$bill_lab = new Billing('irja', $row['nomr'], $dt_bill['idxdaftar'], date('Y-m-d'), 0, 0, $dt_bill['carabayar'], $dt_bill['kd_tl'], 0, $_SESSION['KDUNIT']);
$nota_bill = $bill_lab->simpanBill();
} else {
$bill_lab = new Billing('irna', $row['nomr'], $dt_bill['idxdaftar'], date('Y-m-d'), 0, 0, $dt_bill['carabayar'], $dt_bill['kd_tl'], 0, $_SESSION['KDUNIT']);
$nota_bill = $bill_lab->simpanBill();
}
if ($nota_bill != false) {
// $msg = 'Simpan pemeriksaan lab berhasil';
// $type = 'success';
// update nonota
$query_lab = "UPDATE t_poct set nonota = '$nota_bill' where r_id = {$row['r_id']} and p_id = {$row['p_id']} and nobill = {$row['nobill']} ";
$save_bill = execute($query_lab);
if ($save_bill) {
$qry_daftar = '';
$arr_daftar = [];
$lab_code = $_SESSION['kd_unit_lab_pk'];
$nourut = last_nolab($lab_code);
//check no lab
$tmp_cek = $db->query("SELECT distinct nolab FROM t_orderlabpk_main WHERE NOLAB LIKE '" . $lab_code . date('ym') . "%' ORDER BY NOLAB DESC LIMIT 1");
if ($tmp_cek->numRows() > 0) {
$data = $tmp_cek->fetchAll()[0];
if ($data['nolab'] == $nourut) {
$nourut = last_nolab($lab_code);
}
}
$sql_main = "INSERT INTO t_orderlabpk_main(nolab,idxdaftar,nomr,waktu_pengambilan,ket_pemeriksaan,cito,jenis_form,rajal,aps,tglorder,kdpoly,st_periksa) VALUES ('$nourut','{$dt_bill['idxdaftar']}','{$row['nomr']}','{$arr_insert['tgl_spesimen']}','{$arr_insert['jenis_pemeriksaan']}',0,'BIASA',{$dt_bill['st_rajal']},0,'{$arr_insert['tgl_entri']}',{$dt_bill['kd_tl']},1)";
$tambah_main_order = execute($sql_main);
/*
$sql = "SELECT distinct OrderNumber FROM t_lis_registration WHERE OrderNumber LIKE '".$lab_code.date('ym')."%' ORDER BY OrderNumber DESC LIMIT 1";
$sql = $db->query($sql);
$PRE_NO = $LASTNOLAB = $xLASTNOLAB = null;
$PRE_NO = $lab_code.date('ym');
if($sql->numRows() > 0){
$row = $sql->fetchFirst();
$LASTNOLAB = $row['OrderNumber'];
if(substr($LASTNOLAB, 6) == '999999') {
$xLASTNOLAB = '1'.str_pad('0', 6, '0', STR_PAD_LEFT);
}
else {
if(strlen(substr($LASTNOLAB,6)) < 6) {
$xLASTNOLAB = str_pad( (substr($LASTNOLAB,6)+1), 6, '0', STR_PAD_LEFT);
}
else {
$xLASTNOLAB = str_pad( (substr($LASTNOLAB,6)+1), strlen(substr($LASTNOLAB,6)), '0', STR_PAD_LEFT);
}
}
$nourut = $PRE_NO.$xLASTNOLAB;
}
else {
$nourut = $PRE_NO.'000001';
}
*/
// Reference Bridging
if ($dt_bill['st_rajal']) {
$qry_daftar = "SELECT kelas_daftar,k.kelas as nama_kelas, diagnosa_utama,jenis_penyakit,kdcarabayar,c.nama as carabayar,d.kddokter,d.namadokter,a.kdpoly,p.nama as namapoly,null as noruang, null as namaruang, null as nott,(select distinct nobill from t_billrajal where idxdaftar = a.idxdaftar limit 1) as nobill from t_pendaftaran a
LEFT JOIN icd on icd.icd_code = a.diagnosa_utama
JOIN m_carabayar c on a.kdcarabayar = c.kode
JOIN m_tarifkelas k on a.kelas_daftar = k.kokel
JOIN m_dokter d on a.kddokter = d.kddokter
JOIN m_ruang p on a.kdpoly = p.no
WHERE idxdaftar = {$dt_bill['idxdaftar']} AND nomr = '{$row['nomr']}'";
} else {
$qry_daftar = "SELECT k.kokel as kelas_daftar,r.kelas as nama_kelas,a.icd_masuk as diagnosa_utama,jenis_penyakit,statusbayar as kdcarabayar,c.nama as carabayar,d.kddokter,d.namadokter,null as kdpoly,null as namapoly,noruang,r.nama as namaruang,nott,(select distinct nobill from t_billranap where idxdaftar = a.id_admission limit 1) as nobill FROM t_admission a
LEFT JOIN icd on icd.icd_code = a.icd_masuk
JOIN m_carabayar c on a.statusbayar = c.kode
JOIN m_dokter d on a.dokter_penanggungjawab = d.KDDOKTER
JOIN m_ruang r on a.noruang = r.no
JOIN m_tarifkelas k on r.kelas = k.kelas
WHERE id_admission = {$dt_bill['idxdaftar']} AND nomr = '{$row['nomr']}'";
}
$tmp_daftar = $db->query($qry_daftar);
$arr_daftar = $tmp_daftar->fetchFirst();
// Data Bridging
$DiagnoseID = (!empty($arr_daftar)) ? $arr_daftar['diagnosa_utama'] : '';
$DiagnoseName = (!empty($arr_daftar)) ? preg_replace("/\'/", "`", $arr_daftar['jenis_penyakit']) : '';
$ClassID = (!empty($arr_daftar)) ? $arr_daftar['kelas_daftar'] : 0;
$ClassName = (!empty($arr_daftar)) ? $arr_daftar['nama_kelas'] : '';
$DoctorID = (!empty($arr_daftar)) ? $arr_daftar['kddokter'] : 0;
$DoctorName = (!empty($arr_daftar)) ? $arr_daftar['namadokter'] : '';
$AgreementID = (!empty($arr_daftar)) ? $arr_daftar['kdcarabayar'] : 0;
$AgreementName = (!empty($arr_daftar)) ? $arr_daftar['carabayar'] : '';
if ($dt_bill['st_rajal']) {
$WardID = $arr_daftar['kdpoly'];
$WardName = $arr_daftar['namapoly'];
$ServiceUnitID = 2;
$ServiceUnitName = 'Rawat Jalan';
$RoomID = 0;
$RoomName = '';
$BedID = 0;
$BedName = '';
$AgreementID = $arr_daftar['kdcarabayar'];
$AgreementName = $arr_daftar['carabayar'];
$GuarantorID = 2;
$GuarantorName = 'RAWAT JALAN';
$category_id = 3;
$category_name = 'POCT';
} else {
$WardID = 0;
$WardName = '';
$ServiceUnitID = 1;
$ServiceUnitName = 'Rawat Inap';
$RoomID = $arr_daftar['noruang'];
$RoomName = $arr_daftar['namaruang'];
$BedID = $arr_daftar['nott'];
$BedName = $arr_daftar['nott'];
$AgreementID = $arr_daftar['kdcarabayar'];
$AgreementName = $arr_daftar['carabayar'];
$GuarantorID = 1;
$GuarantorName = 'RAWAT INAP';
$category_id = 3;
$category_name = 'POCT';
}
if (_DBTYPE_ == 'postgre') {
$cito = '0::bit';
}
$arr_LISREG = [
'NoMR' => $row['nomr'],
'VisitNumber' => (($arr_daftar['nobill'] != '') ? $arr_daftar['nobill'] : $dt_bill['idxdaftar']),
'OrderNumber' => $nourut,
'DiagnoseID' => $DiagnoseID,
'DiagnoseName' => $DiagnoseName,
'CITO' => $cito,
'ServiceUnitID' => $ServiceUnitID, // 1 Ranap, 2 Rajal
'ServiceUnitName' => $ServiceUnitName, // Rawat Inap, Rawat Jalan
'GuarantorID' => $GuarantorID, // Penjamin
'GuarantorName' => $GuarantorName,
'AgreementID' => $AgreementID,
'AgreementName' => $AgreementName,
'DoctorID' => $DoctorID,
'DoctorName' => $DoctorName,
'ClassID' => $ClassID,
'ClassName' => $ClassName,
'WardID' => $WardID,
'WardName' => $WardName,
'RoomID' => $RoomID,
'RoomName' => $RoomName,
'BedID' => $BedID,
'BedName' => $BedName,
'RegUserID' => $_SESSION['NIP'],
'RegUserName' => $_SESSION['NAMA_PEGAWAI'],
'OrderDateTime' => date('Y-m-d H:i:s'),
'category_id' => $category_id,
'category_name' => $category_name
];
// echo '<pre>',print_r($arr_LISREG),'</pre>';exit;
$arr_set = array();
foreach ($arr_LISREG as $key => $value) {
if (in_array($key, array('CITO', 'ServiceUnitID', 'GuarantorID', 'AgreementID', 'DoctorID', 'ClassID', 'WardID', 'RoomID', 'BedID'))) {
$value = ($value == '') ? 0 : $value;
$arr_set[$key] = ['value' => $value, 'type' => 'number'];
} else {
$arr_set[$key] = $value;
}
}
$insert_data = "INSERT INTO t_lis_registration " . bind_sql($arr_set);
$save_lis = execute($insert_data);
if ($save_lis) {
if (preg_match("/LSP/", $kode_tindakan)) {
$kode_periksa_lis = $kode_tindakan;
} else {
$ex_kode = explode('.', $kode_tindakan);
$kode_periksa_lis = $ex_kode[1];
}
// add item lis
$arr_LISREGITEM = [];
$arr_LISREGITEM = [
'OrderNumber' => $nourut,
'OrderItemID' => $kode_tindakan,
'OrderItemName' => preg_replace("/\'/", '`', $get_tarif['uraian_tarif']),
'OrderItemDateTime' => date('Y-m-d H:i:s')
];
$insert_lis_item = "INSERT INTO t_lis_regorderitem " . bind_sql($arr_LISREGITEM);
execute($insert_lis_item);
}
}
} else {
// $msg = 'Simpan pemeriksaan lab gagal';
// $type = 'error';
}
//$db->query('DELETE from tmp_cartbayar_detil where idxbayar in (select idxbayar from tmp_cartbayar where IP = \'' . $ip . '\')');
//$db->query('DELETE from tmp_cartbayar where IP = \'' . $ip . '\'');
} else {
$arr_error[] = $row['nobill'];
}
} else {
$arr_error[] = $row['nobill'];
}
}
if (!empty($arr_error)) {
$msg = 'Validasi POCT gagal pada beberapa nobill';
$type = 'error';
} else {
$msg = 'Validasi POCT berhasil';
$type = 'success';
}
} else {
$msg = 'Tidak terdapat nobill yang diproses';
$type = 'error';
}
echo json_encode(['message' => $msg, 'type' => $type]);
exit;
} elseif (array_key_exists('hist_pec', $post) && $post['hist_pec'] == true) {
$arr_validasi_poct = $db_pec->get_results("SELECT p.ID as p_id,p.Lab_PatientID as nomr,p.Location as ruang,r.ID as r_id,r.UnivTestName as DN,r.RValue as rvalue,r.Unit as unit,
r.ANormalFlag as normalflah,convert(varchar, r.TestEndDate, 20) as specimen_dttm,op.FirstName,op.LastName
from Patient as p
left join Result as r on p.ID = r._PID
left join Operator as op on r.OperatiorID = op.OperatorID
where r.RValue <> '' and p.Lab_PatientID = '{$post['nomr']}'
order by r.TestEndDate desc ", 'array');
$html = '<table class="table table-bordered table-striped table-sm" id="tbl_list_item">
<thead>
<tr class="bg-green">
<th width="3%">NO</th>
<th width="5%">NO MR</th>
<th width="15%">Nama Pasien</th>
<th width="8%">Tgl Lahir</th>
<th width="10%">Tempat Layanan/ Operator</th>
<th width="5%">Jenis Pemeriksaan</th>
<th width="10%">Tgl Spesimen</th>
<th width="5%">Nilai</th>
<th width="5%">Unit</th>
</tr>
</thead>
<tbody>';
$no = 1;
foreach ($arr_validasi_poct as $ind => $item) {
$tempat = explode('^', $item['ruang']);
$tempat_layanana = (preg_match('/IRD|IGD/', $tempat[1])) ? 'rajal' : 'ranap';
$tmp_pasien = $db->query("SELECT nama,tgllahir from m_pasien where nomr = '{$item['nomr']}'");
$nama_pasien = $tgl_lahir = '';
if ($tmp_pasien->numRows() > 0) {
$dt_pasien = $tmp_pasien->fetchFirst();
$nama_pasien = $dt_pasien['nama'];
$tgl_lahir = $dt_pasien['tgllahir'];
}
$html .= '<tr>
<td>' . $no++ . '</td>
<td>' . $item['nomr'] . '</td>
<td>' . $nama_pasien . '</td>
<td>' . $tgl_lahir . '</td>
<td>' . $tempat[1] . '</td>
<td>' . $item['FirstName'] . ' ' . $item['LastName'] . '</td>
<td>' . $item['DN'] . '</td>
<td>' . $item['rvalue'] . '</td>
<td>' . $item['unit'] . '</td>
</tr>';
}
$html .= '</tbody></table>';
echo $html;
exit;
} elseif (array_key_exists('validate_pec', $post) && $post['validate_pec'] == true) {
global $db_pec;
global $db;
$no_pemeriksaan = !empty($post['norm']) ? " and SUBSTRING(p.Lab_PatientID, 1,8) = '{$post['norm']}'" : '';
$tmp_list_trans = $db_pec->get_results("SELECT p.ID as p_id,p.Lab_PatientID as nomr,p.Location as ruang,r.ID as r_id,r.UnivTestName as DN,r.RValue as rvalue,
r.Unit as unit,r.ANormalFlag as normalflah,convert(varchar, r.TestEndDate, 20) as specimen_dttm,op.FirstName,op.LastName, convert(varchar, p.lastUpdDatetime, 20) as lastUpdDatetime
from Patient as p
left join Result as r on p.ID = r._PID
left join Operator as op on r.OperatiorID = op.OperatorID
where r.RValue <> '' and convert(date,r.TestEndDate) = '" . $post['tanggal_order'] . "' $no_pemeriksaan
and LEN(p.Lab_PatientID) >= 10
order by r.TestEndDate, p.Lab_PatientID desc", 'array');
$arr_tempat = ['' => 'Semua Ruang'];
$arr_pasien = [];
if (!empty($tmp_list_trans)) {
$no = 1;
foreach ($tmp_list_trans as $k => $list) {
//Cari NORM pasien sesuai nomer pemeriksaan
if (strlen($list['nomr']) == 20) {
$order_poct_sql = $db->query("SELECT order_poct.*,m_pasien.nama as nama_pasien, m_ruang.nama as ruangan, m_ruang.no as kode_ruangan, m_perawat.nama as operator, m_pasien.tgllahir as tgl_lahir from order_poct
join m_pasien on m_pasien.nomr = order_poct.norm
join m_ruang on m_ruang.no = order_poct.ruang_id
join m_perawat on m_perawat.idperawat = order_poct.operator_id
where no_pemeriksaan = '{$list['nomr']}' and to_char(tanggal, 'YYYY-mm-dd') = '{$post['tanggal_order']}' and (is_valid = 2 or is_valid = 0 or is_valid is null) ");
} else {
$order_poct_sql = $db->query("SELECT order_poct.*,m_pasien.nama as nama_pasien, m_ruang.nama as ruangan, m_ruang.no as kode_ruangan, m_perawat.nama as operator, m_pasien.tgllahir as tgl_lahir from order_poct
join m_pasien on m_pasien.nomr = order_poct.norm
join m_ruang on m_ruang.no = order_poct.ruang_id
join m_perawat on m_perawat.idperawat = order_poct.operator_id
where upper(order_number) = '{$list['nomr']}' and to_char(tanggal, 'YYYY-mm-dd') = '{$post['tanggal_order']}' and (is_valid = 2 or is_valid = 0 or is_valid is null) ");
}
$order_poct = $order_poct_sql->fetchAll()[0];
if (!empty($order_poct)) {
if (empty($order_poct['no_nota'])) {
$arr_pasien[$k]['no'] = $no++;
$arr_pasien[$k]['nama_pasien'] = $order_poct['nama_pasien'];
$arr_pasien[$k]['norm'] = $order_poct['norm'];
$arr_pasien[$k]['no_pemeriksaan'] = $order_poct['no_pemeriksaan'];
$arr_pasien[$k]['order_number'] = $order_poct['order_number'];
$arr_pasien[$k]['tgl_lahir'] = $order_poct['tgl_lahir'];
$arr_pasien[$k]['ruangan'] = $order_poct['ruangan'];
$arr_pasien[$k]['kode_ruangan'] = $order_poct['kode_ruangan'];
$arr_pasien[$k]['operator'] = $order_poct['operator'];
$arr_pasien[$k]['jenis'] = $list['DN'];
$arr_pasien[$k]['tgl_spesimen'] = $list['specimen_dttm'];
$arr_pasien[$k]['nilai'] = $list['rvalue'];
$arr_pasien[$k]['unit'] = $list['unit'];
$arr_pasien[$k]['p_id'] = $list['p_id'];
$arr_pasien[$k]['no_billing'] = $order_poct['no_billing'];
$arr_pasien[$k]['flag'] = $order_poct['flag'];
$arr_pasien[$k]['idxdaftar'] = $order_poct['idxdaftar'];
$arr_pasien[$k]['created_at'] = $order_poct['created_at'];
$arr_pasien[$k]['order_id'] = $order_poct['id'];
$arr_pasien[$k]['lastUpdDatetime'] = $list['lastUpdDatetime'];
}
}
}
echo json_encode(['pasien' => $arr_pasien, 'ruang' => '']);
}
} elseif (array_key_exists('validasi_poct', $post) && $post['validasi_poct'] == true) {
$arr_post = $post['input'];
$ip = getRealIpAddr();
$arr_insert['tgl_entri'] = date('Y-m-d H:i:s');
$msg = 'Validasi Berhasil';
$type = 'success';
$arr_validasi_poct = [];
foreach ($arr_post as $ind => $item) {
$arr_validasi_poct[$item['norm']]['norm'] = $item['norm'];
$arr_validasi_poct[$item['norm']]['order_id'] = $item['order_id'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['norm'] = $item['norm'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['idxdaftar'] = $item['idxdaftar'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['no_pemeriksaan'] = $item['no_pemeriksaan'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['order_number'] = $item['order_number'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['nama_pasien'] = $item['nama_pasien'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['tgl_lahir'] = $item['tgl_lahir'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['kode_ruangan'] = $item['kode_ruangan'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['ruangan'] = $item['ruangan'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['operator'] = $item['operator'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['jenis'] = $item['jenis'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['tgl_spesimen'] = $item['tgl_spesimen'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['nilai'] = $item['nilai'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['unit'] = $item['unit'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['no_billing'] = $item['no_billing'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['p_id'] = $item['p_id'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['is_valid'] = $item['is_valid'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['flag'] = $item['flag'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['created_at'] = $item['created_at'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['order_id'] = $item['order_id'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['is_proses'] = $item['is_proses'];
$arr_validasi_poct[$item['norm']]['detail'][$item['no_pemeriksaan']]['lastUpdDatetime'] = $item['lastUpdDatetime'];
}
$xx = '';
foreach ($arr_validasi_poct as $ind => $validasi) {
$norm_ind = '';
$is_nobill = '';
foreach ($validasi['detail'] as $x => $item) {
if ($item['is_proses'] == 1) {
if ($item['is_valid'] == 1) {
//cek apakah ada pendingan order atasnya ?
$query_poct = $db->query("select * from order_poct where created_at < '{$item['created_at']}' and idxdaftar = '{$item['idxdaftar']}' and norm = '{$item['norm']}' and is_valid is null");
if ($query_poct->numRows() > 0) {
$orders = $query_poct->fetchAll();
foreach ($orders as $order) {
$query_order = "UPDATE order_poct set is_valid = '3' where no_pemeriksaan = '{$order['no_pemeriksaan']}' and norm = '{$order['norm']}' ";
$save_order = execute($query_order);
}
}
//Cari Kode Tarif
$sql_poct = $db->query("select opd.tarif_rs_id ,opd.kode_tarif_rs, op.carabayar_id from order_poct op
join order_poct_detail opd on op.id = opd.order_poct_id
where no_pemeriksaan = '{$item['no_pemeriksaan']}'");
$kode_tindakan = '';
if ($sql_poct->numRows() > 0) {
$poct = $sql_poct->fetchAll()[0];
//foreach ($data_poct as $poct) {
$kode_tindakan = $poct['kode_tarif_rs'];
$get_tarif = getTarif($kode_tindakan);
$jasa_sarana = ($get_tarif['jasa_sarana'] != '') ? $get_tarif['jasa_sarana'] : 0;
$jasa_pelayanan = ($get_tarif['jasa_pelayanan'] != '') ? $get_tarif['jasa_pelayanan'] : 0;
$jasa_anastesi = ($get_tarif['jasa_anastesi'] != '') ? $get_tarif['jasa_anastesi'] : 0;
$dokter_mod = ($post['dokter_mod'] != '') ? $post['dokter_mod'] : '';
$save = "INSERT into tmp_cartbayar " . bind_sql([
'kodetarif' => $kode_tindakan,
'ip' => $ip,
'qty' => ['value' => 1, 'type' => 'number'],
'poly' => ['value' => $item['kode_ruangan'], 'type' => 'number'],
'unit' => ['value' => $_SESSION['KDUNIT'], 'type' => 'number'],
'tarif' => ['value' => $get_tarif['jumlah'], 'type' => 'number'],
'discount' => ['value' => 0, 'type' => 'number'],
'tottarif' => ['value' => $get_tarif['jumlah'], 'type' => 'number'],
'jasa_sarana' => ['value' => $jasa_sarana, 'type' => 'number'],
'jasa_pelayanan' => ['value' => $jasa_pelayanan, 'type' => 'number'],
'jasa_anastesi' => ['value' => $jasa_anastesi, 'type' => 'number'],
'kddokter' => ['value' => $dokter_mod, 'type' => 'number']
]);
$result_tmp = execute($save . " RETURNING idxbayar");
$idxbayar = $result_tmp->fetchFirst()['idxbayar'];
//ranap
if ($item['flag'] == 1) {
$is_lanjut = true;
$xx .= $item['norm'] . ' - ';
//if($x == '11571099202309070003'){
// var_dump($norm_ind != $item['norm']); die();
//}
//if($norm_ind != $item['norm']){
$bill_lab = new Billing('irna', $item['norm'], $item['idxdaftar'], date('Y-m-d'), 0, 0, $poct['carabayar_id'], $item['kode_ruangan'], 0, $_SESSION['KDUNIT']);
$nota_bill = $bill_lab->simpanBill();
if ($nota_bill != false) {
$is_nobill = $nota_bill;
$query_order = "UPDATE order_poct set no_nota = '$is_nobill' where no_pemeriksaan = '{$item['no_pemeriksaan']}' and norm = '{$item['norm']}' ";
$save_order = execute($query_order);
$is_lanjut = true;
} else {
$is_lanjut = false;
}
//}else{
//if($x == '11567981202309070001'){
// print_r($nota_bill); die();
//}
// $bill_lab = new Billing('irna', $item['norm'], $item['idxdaftar'], date('Y-m-d'), 0, 0, $poct['carabayar_id'], $item['kode_ruangan'], 0, $_SESSION['KDUNIT']);
// $nota_bill = $bill_lab->simpanBill($is_nobill);
// $query_order = "UPDATE order_poct set no_nota = '$is_nobill' where no_pemeriksaan = '{$item['no_pemeriksaan']}' and norm = '{$item['norm']}' ";
// $save_order = execute($query_order);
//}
}
if ($is_lanjut == true) {
$query_lab = "UPDATE order_poct set is_valid = '{$item['is_valid']}' where no_pemeriksaan = '{$item['no_pemeriksaan']}' and norm = '{$item['norm']}' ";
$save_bill = execute($query_lab);
if ($save_bill) {
$lab_code = $_SESSION['kd_unit_lab_pk'];
$nourut = $item['no_pemeriksaan'];
$tmp_cek = $db->query("SELECT distinct nolab FROM t_orderlabpk_main WHERE NOLAB LIKE '" . $lab_code . date('ym') . "%' ORDER BY NOLAB DESC LIMIT 1");
if ($tmp_cek->numRows() > 0) {
$data = $tmp_cek->fetchAll()[0];
if ($data['nolab'] == $nourut) {
$nourut = $item['no_pemeriksaan'];
}
}
$sql_main = "INSERT INTO t_orderlabpk_main(nolab,idxdaftar,nomr,waktu_pengambilan,ket_pemeriksaan,cito,jenis_form,rajal,aps,tglorder,kdpoly,st_periksa)
VALUES
('$nourut','{$item['no_billing']}','{$item['norm']}','{$item['tgl_spesimen']}','{$item['jenis']}',0,'BIASA',
{$item['flag']},0,'{$arr_insert['tgl_entri']}',{$item['kode_ruangan']},1)";
$tambah_main_order = execute($sql_main);
// Reference Bridging
//$item['flag'] == 1 -> ranap
if ($item['flag'] == 1) {
$qry_daftar = "SELECT k.kokel as kelas_daftar,r.kelas as nama_kelas,a.icd_masuk as diagnosa_utama,jenis_penyakit,statusbayar as kdcarabayar,c.nama as carabayar,d.kddokter,d.namadokter,null as kdpoly,null as namapoly,noruang,r.nama as namaruang,nott,(select distinct nobill from t_billranap where idxdaftar = a.id_admission limit 1) as nobill FROM t_admission a
LEFT JOIN icd on icd.icd_code = a.icd_masuk
JOIN m_carabayar c on a.statusbayar = c.kode
JOIN m_dokter d on a.dokter_penanggungjawab = d.KDDOKTER
JOIN m_ruang r on a.noruang = r.no
JOIN m_tarifkelas k on r.kelas = k.kelas
WHERE id_admission = '{$item['idxdaftar']}' AND nomr = '{$item['norm']}'";
}
$sql_dokter = $db->query("SELECT kddokter,namadokter
FROM m_dokter
WHERE kddokter = '" . $dokter_mod . "' and aktif = 1");
$dokter_mod = $sql_dokter->fetchAll()[0];
$dokter_mod_id = '';
$dokter_mode_name = '';
if (!empty($dokter_mod)) {
$dokter_mod_id = $dokter_mod['kddokter'];
$dokter_mode_name = $dokter_mod['namadokter'];
}
$tmp_daftar = $db->query($qry_daftar);
$arr_daftar = $tmp_daftar->fetchFirst();
$DiagnoseID = (!empty($arr_daftar)) ? $arr_daftar['diagnosa_utama'] : '';
$DiagnoseName = (!empty($arr_daftar)) ? preg_replace("/\'/", "`", $arr_daftar['jenis_penyakit']) : '';
$ClassID = (!empty($arr_daftar)) ? $arr_daftar['kelas_daftar'] : 0;
$ClassName = (!empty($arr_daftar)) ? $arr_daftar['nama_kelas'] : '';
$DoctorID = (!empty($arr_daftar)) ? $arr_daftar['kddokter'] : 0;
$DoctorName = (!empty($arr_daftar)) ? $arr_daftar['namadokter'] : '';
$AgreementID = (!empty($arr_daftar)) ? $arr_daftar['kdcarabayar'] : 0;
$AgreementName = (!empty($arr_daftar)) ? $arr_daftar['carabayar'] : '';
if ($item['flag'] == 1) {
$WardID = 0;
$WardName = '';
$ServiceUnitID = 1;
$ServiceUnitName = 'Rawat Inap';
$RoomID = $arr_daftar['noruang'];
$RoomName = $arr_daftar['namaruang'];
$BedID = $arr_daftar['nott'];
$BedName = $arr_daftar['nott'];
$AgreementID = $arr_daftar['kdcarabayar'];
$AgreementName = $arr_daftar['carabayar'];
$GuarantorID = 1;
$GuarantorName = 'RAWAT INAP';
$category_id = 3;
$category_name = 'POCT';
$dokter_id = $dokter_mod_id;
$dokter_name = $dokter_mode_name;
}
if (_DBTYPE_ == 'postgre') {
$cito = '0::bit';
}
$arr_LISREG = [
'NoMR' => $item['norm'],
'VisitNumber' => $item['no_billing'],
'OrderNumber' => $item['no_pemeriksaan'],
'DiagnoseID' => $DiagnoseID,
'DiagnoseName' => $DiagnoseName,
'CITO' => $cito,
'ServiceUnitID' => $ServiceUnitID, // 1 Ranap, 2 Rajal
'ServiceUnitName' => $ServiceUnitName, // Rawat Inap, Rawat Jalan
'GuarantorID' => $GuarantorID, // Penjamin
'GuarantorName' => $GuarantorName,
'AgreementID' => $AgreementID,
'AgreementName' => $AgreementName,
'DoctorID' => $DoctorID,
'DoctorName' => $DoctorName,
'ClassID' => $ClassID,
'ClassName' => $ClassName,
'WardID' => $WardID,
'WardName' => $WardName,
'RoomID' => $RoomID,
'RoomName' => $RoomName,
'BedID' => $BedID,
'BedName' => $BedName,
'RegUserID' => $_SESSION['NIP'],
'RegUserName' => $_SESSION['NAMA_PEGAWAI'],
'OrderDateTime' => $item['lastUpdDatetime'],
'category_id' => $category_id,
'category_name' => $category_name,
'dokter_id' => $dokter_id,
'dokter_name' => $dokter_name
];
$arr_set = array();
foreach ($arr_LISREG as $key => $value) {
if (in_array($key, array('CITO', 'ServiceUnitID', 'GuarantorID', 'AgreementID', 'DoctorID', 'ClassID', 'WardID', 'RoomID', 'BedID'))) {
$value = ($value == '') ? 0 : $value;
$arr_set[$key] = ['value' => $value, 'type' => 'number'];
} else {
$arr_set[$key] = $value;
}
}
$insert_data = "INSERT INTO t_lis_registration " . bind_sql($arr_set);
$save_lis = execute($insert_data);
if ($save_lis) {
if (preg_match("/LSP/", $kode_tindakan)) {
$kode_periksa_lis = $kode_tindakan;
} else {
$ex_kode = explode('.', $kode_tindakan);
$kode_periksa_lis = $ex_kode[1];
}
// add item lis
$arr_LISREGITEM = [];
$arr_LISREGITEM = [
'OrderNumber' => $item['no_pemeriksaan'],
'OrderItemID' => $kode_tindakan,
'OrderItemName' => preg_replace("/\'/", '`', $get_tarif['uraian_tarif']),
'OrderItemDateTime' => $item['lastUpdDatetime'],
'hasil' => $item['nilai']
];
$insert_lis_item = "INSERT INTO t_lis_regorderitem " . bind_sql($arr_LISREGITEM);
execute($insert_lis_item);
}
} else {
$msg = 'Validasi POCT gagal, gagal update no nota!';
$type = 'error';
}
} else {
$msg = 'Validasi POCT gagal, gagal create Billing!';
$type = 'error';
}
//}
} else {
$msg = 'Validasi POCT gagal, No Pemeriksaan POCT tidak ditemukan!';
$type = 'error';
}
} else {
$query_lab = "UPDATE order_poct set is_valid = '{$item['is_valid']}' where no_pemeriksaan = '{$item['no_pemeriksaan']}' and norm = '{$item['norm']}' ";
$save_bill = execute($query_lab);
}
$norm_ind = $item['norm'];
$is_nobill = $nota_bill;
} else {
$query_lab = "UPDATE order_poct set is_valid = '3' where no_pemeriksaan = '{$item['no_pemeriksaan']}' and norm = '{$item['norm']}' ";
$save_bill = execute($query_lab);
}
}
$sql_order_poct = $db->query("select * from order_poct where id = '{$validasi['order_id']}'");
$data_poct = $sql_order_poct->fetchAll()[0];
foreach ($validasi['detail'] as $is => $data) {
$sql_poct = $db->query("select * from order_poct where id = '{$data['order_id']}'");
$poct = $sql_poct->fetchAll()[0];
if (!empty($poct['no_nota'])) {
$sql_bill = $db->query("select * from t_billranap where nonota = '{$poct['no_nota']}'");
$bill = $sql_bill->fetchAll()[0];
$query_poct = "UPDATE order_poct set no_nota = '{$data_poct['no_nota']}' where id = '{$poct['id']}' and norm = '{$item['norm']}' ";
$save_poct = execute($query_poct);
$query_bill = "UPDATE t_billranap set nonota = '{$data_poct['no_nota']}' where idxbill = '{$bill['idxbill']}' and nomr = '{$bill['nomr']}' ";
$save_bill = execute($query_bill);
}
}
}
echo json_encode(['message' => $msg, 'type' => $type]);
exit;
} elseif (array_key_exists('rekap_poct', $post) && $post['rekap_poct'] == true) {
global $db_pec;
global $db;
$is_time = false;
if (!empty($post['time_order_start']) && !empty($post['time_order_end'])) {
$date_start = date_create($post['tanggal_order_start'] . ' ' . $post['time_order_start']);
$date_start = date_format($date_start, "Y-m-d H:i:s");
$date_end = date_create($post['tanggal_order_start'] . ' ' . $post['time_order_end']);
$date_end = date_format($date_end, "Y-m-d H:i:s");
$is_time = true;
}
if ($is_time) {
$tmp_list_trans = $db_pec->get_results("SELECT p.ID as p_id,p.Lab_PatientID as nomr,p.Location as ruang,r.ID as r_id,r.UnivTestName as DN,r.RValue as rvalue,
r.Unit as unit,r.ANormalFlag as normalflah,convert(varchar, r.TestEndDate, 20) as specimen_dttm,op.FirstName,op.LastName, convert(varchar, p.lastUpdDatetime, 20) as lastUpdDatetime, r.InstrSectionID
from Patient as p
left join Result as r on p.ID = r._PID
left join Operator as op on r.OperatiorID = op.OperatorID
where r.RValue <> '' and convert(datetime,r.TestEndDate) between CONVERT(datetime, '" . $date_start . "' ) and CONVERT(datetime, '" . $date_end . "')
order by r.TestEndDate, p.Lab_PatientID desc", 'array');
} else {
$tmp_list_trans = $db_pec->get_results("SELECT p.ID as p_id,p.Lab_PatientID as nomr,p.Location as ruang,r.ID as r_id,r.UnivTestName as DN,r.RValue as rvalue,
r.Unit as unit,r.ANormalFlag as normalflah,convert(varchar, r.TestEndDate, 20) as specimen_dttm,op.FirstName,op.LastName, convert(varchar, p.lastUpdDatetime, 20) as lastUpdDatetime, r.InstrSectionID
from Patient as p
left join Result as r on p.ID = r._PID
left join Operator as op on r.OperatiorID = op.OperatorID
where r.RValue <> '' and convert(date,r.TestEndDate) = '" . $date_start . "'
order by r.TestEndDate, p.Lab_PatientID desc", 'array');
}
$arr_pasien = [];
if (count($tmp_list_trans) > 0) {
$no = 1;
foreach ($tmp_list_trans as $ind => $list) {
$is_data = false;
$data_poct = '';
if (strlen($list['nomr']) > 10) {
if (strlen($list['nomr']) == 20) {
$order_poct_sql = $db->query("SELECT order_poct.*,m_pasien.nama as nama_pasien, m_ruang.nama as ruangan, m_ruang.no as kode_ruangan, m_perawat.nama as operator, m_pasien.tgllahir as tgl_lahir from order_poct
join m_pasien on m_pasien.nomr = order_poct.norm
join m_ruang on m_ruang.no = order_poct.ruang_id
join m_perawat on m_perawat.idperawat = order_poct.operator_id
where no_pemeriksaan = '{$list['nomr']}' and to_char(tanggal, 'YYYY-mm-dd') = '{$post['tanggal_order_start']}' and (is_valid = 2 or is_valid = 0 or is_valid is null) ");
} else {
$order_poct_sql = $db->query("SELECT order_poct.*,m_pasien.nama as nama_pasien, m_ruang.nama as ruangan, m_ruang.no as kode_ruangan, m_perawat.nama as operator, m_pasien.tgllahir as tgl_lahir from order_poct
join m_pasien on m_pasien.nomr = order_poct.norm
join m_ruang on m_ruang.no = order_poct.ruang_id
join m_perawat on m_perawat.idperawat = order_poct.operator_id
where upper(order_number) = '{$list['nomr']}' and to_char(tanggal, 'YYYY-mm-dd') = '{$post['tanggal_order_start']}' and (is_valid = 2 or is_valid = 0 or is_valid is null) ");
}
$order_poct = $order_poct_sql->fetchAll()[0];
if (!empty($order_poct)) {
$is_data = true;
$data_poct = $order_poct;
}
}
$arr_pasien[$ind]['no'] = $no++;
$arr_pasien[$ind]['nomr'] = ($is_data) ? $data_poct['norm'] : $list['nomr'];
$arr_pasien[$ind]['nama_pasien'] = ($is_data) ? $data_poct['nama_pasien'] : $list['FirstName'] . ' ' . $list['LastName'];
$arr_pasien[$ind]['no_billing'] = ($is_data) ? $data_poct['no_billing'] : '';
$arr_pasien[$ind]['date'] = $list['specimen_dttm'];
$arr_pasien[$ind]['InstrSectionID'] = $list['InstrSectionID'];
$arr_pasien[$ind]['ruang'] = $list['ruang'];
$arr_pasien[$ind]['hasil'] = $list['rvalue'];
$arr_pasien[$ind]['unit'] = $list['unit'];
$arr_pasien[$ind]['data_order'] = ($is_data) ? "ADA" : "TIDAK";
}
echo json_encode(['pasien' => $arr_pasien]);
}
}
+130
View File
@@ -0,0 +1,130 @@
<?php
if (!session_id()) {
session_start();
}
require_once 'main.php';
require_once('SQLServerDb.php');
$db_pec = new SQLServerDb(
$_ENV['PEC_DB_USER'],
$_ENV['PEC_DB_PASS'],
$_ENV['PEC_DB_NAME'],
$_ENV['PEC_DB_HOST']
);
$post = $_REQUEST;
if (array_key_exists('rekap_poct', $post) && $post['rekap_poct'] == true) {
global $db_pec;
global $db;
$is_time= false;
if(!empty($post['time_order_start']) && !empty($post['time_order_end'])){
$date_start = date_create($post['tanggal_order_start'] .' '. $post['time_order_start']);
$date_start = date_format($date_start, "Y-m-d H:i:s");
$date_end = date_create($post['tanggal_order_start'] .' '. $post['time_order_end']);
$date_end = date_format($date_end, "Y-m-d H:i:s");
$is_time = true;
}
if($is_time){
$tmp_list_trans = $db_pec->get_results("SELECT p.ID as p_id,p.Lab_PatientID as nomr,p.Location as ruang,r.ID as r_id,r.UnivTestName as DN,r.RValue as rvalue,
r.Unit as unit,r.ANormalFlag as normalflah,convert(varchar, r.TestEndDate, 20) as specimen_dttm,op.FirstName,op.LastName, convert(varchar, p.lastUpdDatetime, 20) as lastUpdDatetime, r.InstrSectionID
from Patient as p
left join Result as r on p.ID = r._PID
left join Operator as op on r.OperatiorID = op.OperatorID
where convert(datetime,r.TestEndDate) between CONVERT(datetime, '".$date_start."' ) and CONVERT(datetime, '".$date_end."')
order by r.TestEndDate, p.Lab_PatientID desc", 'array');
}else{
$tmp_list_trans = $db_pec->get_results("SELECT p.ID as p_id,p.Lab_PatientID as nomr,p.Location as ruang,r.ID as r_id,r.UnivTestName as DN,r.RValue as rvalue,
r.Unit as unit,r.ANormalFlag as normalflah,convert(varchar, r.TestEndDate, 20) as specimen_dttm,op.FirstName,op.LastName, convert(varchar, p.lastUpdDatetime, 20) as lastUpdDatetime, r.InstrSectionID
from Patient as p
left join Result as r on p.ID = r._PID
left join Operator as op on r.OperatiorID = op.OperatorID
where convert(date,r.TestEndDate) = '".$date_start."'
order by r.TestEndDate, p.Lab_PatientID desc", 'array');
}
$arr_pasien = [];
if(count($tmp_list_trans) > 0){
$no = 1;
foreach($tmp_list_trans as $ind => $list){
$is_data = false;
$data_poct = '';
if(strlen($list['nomr']) > 10){
if(strlen($list['nomr']) == 20){
$order_poct_sql = $db->query("SELECT order_poct.*,m_pasien.nama as nama_pasien, m_ruang.nama as ruangan, m_ruang.no as kode_ruangan, m_perawat.nama as operator, m_pasien.tgllahir as tgl_lahir from order_poct
join m_pasien on m_pasien.nomr = order_poct.norm
join m_ruang on m_ruang.no = order_poct.ruang_id
join m_perawat on m_perawat.idperawat = order_poct.operator_id
where no_pemeriksaan = '{$list['nomr']}'
--and (is_valid = 2 or is_valid = 0 or is_valid is null)
");
}else{
$order_poct_sql = $db->query("SELECT order_poct.*,m_pasien.nama as nama_pasien, m_ruang.nama as ruangan, m_ruang.no as kode_ruangan, m_perawat.nama as operator, m_pasien.tgllahir as tgl_lahir from order_poct
join m_pasien on m_pasien.nomr = order_poct.norm
join m_ruang on m_ruang.no = order_poct.ruang_id
join m_perawat on m_perawat.idperawat = order_poct.operator_id
where upper(order_number) = '{$list['nomr']}'
--and (is_valid = 2 or is_valid = 0 or is_valid is null)
");
}
$order_poct = $order_poct_sql->fetchAll()[0];
if(!empty($order_poct)){
$is_data = true;
$data_poct = $order_poct;
}
}
$arr_pasien[$ind]['no'] = $no++;
$arr_pasien[$ind]['nomr'] = ($is_data) ? $data_poct['norm'] : $list['nomr'];
$arr_pasien[$ind]['nama_pasien'] = ($is_data) ? $data_poct['nama_pasien'] : '';
$arr_pasien[$ind]['no_billing'] = ($is_data) ? $data_poct['no_billing'] : '' ;
$arr_pasien[$ind]['date'] = $list['specimen_dttm'];
$arr_pasien[$ind]['InstrSectionID'] = $list['InstrSectionID'];
$arr_pasien[$ind]['ruang'] = $list['ruang'];
$arr_pasien[$ind]['hasil'] = $list['rvalue'];
$arr_pasien[$ind]['unit'] = $list['unit'];
$arr_pasien[$ind]['data_order'] = ($is_data) ? "ADA" :"TIDAK";
}
}
}
?>
<div class="row">
<div class="col-md-12">
<table class="table table-striped">
<tr>
<td>No</td>
<td>Norm</td>
<td>Nama</td>
<td>No Billing</td>
<td>Tanggal Pemeriksaan</td>
<td>Analyser</td>
<td>Hasil</td>
<td>Ruangan</td>
<td>Order</td>
</tr>
<?php
$no = 1;
foreach($arr_pasien as $ind => $item) : ?>
<tr>
<td><?= $no++ ?></td>
<td><?= $item['nomr'] ?></td>
<td><?= $item['nama_pasien'] ?></td>
<td><?= $item['no_billing'] ?></td>
<td><?= $item['date'] ?></td>
<td><?= $item['InstrSectionID'] ?></td>
<td><?= $item['hasil'] .' ' . $item['unit'] ?></td>
<td><?= $item['ruang'] ?></td>
<td><?= $item['data_order'] ?></td>
</tr>
<?php endforeach ?>
</table>
</div>
</div>
+27
View File
@@ -0,0 +1,27 @@
<?php
if (!session_id()) {
session_start();
}
require_once 'core/main.php';
require_once (_DOCROOT_.'vendor/autoload.php');
require_once 'main.php';
require_once('SQLServerDb.php');
$db_pec = new SQLServerDb(
$_ENV['PEC_DB_USER'],
$_ENV['PEC_DB_PASS'],
$_ENV['PEC_DB_NAME'],
$_ENV['PEC_DB_HOST']
);
$post = $_REQUEST;
print_r($post); die();
// reference the Dompdf namespace
use Dompdf\Dompdf;
if (array_key_exists('rekap_poct', $post) && $post['rekap_poct'] == true) {
print_r($post); die();
}
+51
View File
@@ -0,0 +1,51 @@
<?php
class SQLSRV {
protected $connection = null;
public function connect() {
// we don't need to connect twice
if ( $this->connection ) {
return;
}
// data for making connection
$mssql_server = $_ENV['FARMASI_HOST'];
$mssql_data = array("UID" => $_ENV['FARMASI_DB_USER'],
"PWD" => $_ENV['FARMASI_DB_PASS'],
"Database" => $_ENV['FARMASI_DB_NAME']);
// try to connect
$this->connection = sqlsrv_connect($mssql_server, $mssql_data);
if($this->connection){
// silent
}
else {
// log_message('error','Failed to connect with parameter[] = ['.$mssql_server.','.implode(',', $mssql_data).']');
log_message('error','Failed to connect with error = ['.print_r( sqlsrv_errors(), true).']');
return 'Failed to connect to host';
}
}
public function getData ($query) {
// reset results; is this really needed as object's variable? Can't it be just local function's variable??
$this->data_array = array();
$result = $this->query($query);
while ($row = sqlsrv_fetch_array($result)) {
$this->data_array[] = $row;
}
return $this->data_array;
}
public function query($query) {
if($this->connection == null) {
$this->connect();
}
$result = sqlsrv_query($this->connection, $query);
if(!$result) {
log_message('error','Failed query : '.$query);
}
// $result = sqlsrv_query($this->connection, $query) or die("This Query didn't work.. [QUERY = ".$query."]");
return $result;
}
}
+552
View File
@@ -0,0 +1,552 @@
<?php
class SSP {
/**
* Create the data output array for the DataTables rows
*
* @param array $columns Column information array
* @param array $data Data from the SQL get
* @return array Formatted data in a row based format
*/
static function data_output ( $columns, $data )
{
$out = array();
for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) {
$row = array();
for ( $j=0, $jen=count($columns) ; $j<$jen ; $j++ ) {
$column = $columns[$j];
$column['db'] = self::change_column($column['db']);
$columns[$j]['db'] = self::change_column($columns[$j]['db']);
// Is there a formatter?
if ( isset( $column['formatter'] ) ) {
if(empty($column['db'])){
$row[ $column['dt'] ] = $column['formatter']( $data[$i] );
}
else{
$row[ $column['dt'] ] = $column['formatter']( $data[$i][ $column['db'] ], $data[$i] );
}
}
else {
if(!empty($column['db'])){
$row[ $column['dt'] ] = $data[$i][ $columns[$j]['db'] ];
}
else{
$row[ $column['dt'] ] = "";
}
}
}
$out[] = $row;
}
return $out;
}
/**
* Database connection
*
* Obtain an PHP PDO connection from a connection details array
*
* @param array $conn SQL connection details. The array should have
* the following properties
* * host - host name
* * db - database name
* * user - user name
* * pass - user password
* @return resource PDO connection
*/
static function db ( $conn )
{
if ( is_array( $conn ) ) {
return self::sql_connect( $conn );
}
return $conn;
}
/**
* Paging
*
* Construct the LIMIT clause for server-side processing SQL query
*
* @param array $request Data sent to server by DataTables
* @param array $columns Column information array
* @return string SQL limit clause
*/
static function limit ( $request, $columns )
{
$limit = '';
if (isset($request['start']) && $request['length'] != -1 ) {
$limit = "LIMIT ".($request['length'])." OFFSET ".($request['start']);
}
return $limit;
}
/**
* Ordering
*
* Construct the ORDER BY clause for server-side processing SQL query
*
* @param array $request Data sent to server by DataTables
* @param array $columns Column information array
* @return string SQL order by clause
*/
static function order ( $request, $columns )
{
$order = '';
if ( isset($request['order']) && count($request['order']) ) {
$orderBy = array();
$dtColumns = self::pluck( $columns, 'dt' );
for ( $i=0, $ien=count($request['order']) ; $i<$ien ; $i++ ) {
// Convert the column index into the column data property
$columnIdx = intval($request['order'][$i]['column']);
$requestColumn = $request['columns'][$columnIdx];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
if ( $requestColumn['orderable'] == 'true' ) {
$dir = $request['order'][$i]['dir'] === 'asc' ?
'ASC' :
'DESC';
$column['db'] = (preg_match("/ as /i", $column['db'])) ? self::change_column($column['db']) : $column['db'];
$orderBy[] = ''.$column['db'].' '.$dir;
}
}
if ( count( $orderBy ) ) {
$order = 'ORDER BY '.implode(', ', $orderBy);
}
}
return $order;
}
/**
* Searching / Filtering
*
* Construct the WHERE clause for server-side processing SQL query.
*
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here performance on large
* databases would be very poor
*
* @param array $request Data sent to server by DataTables
* @param array $columns Column information array
* @param array $bindings Array of values for PDO bindings, used in the
* sql_exec() function
* @return string SQL where clause
*/
static function filter ( $request, $columns, &$bindings )
{
$globalSearch = array();
$columnSearch = array();
$dtColumns = self::pluck( $columns, 'dt' );
if ( isset($request['search']) && $request['search']['value'] != '' ) {
$str = $request['search']['value'];
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
$requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
if(preg_match("/ as /i", $column['db']))
{
$exp_column = explode(' as ', $column['db']);
$column['db'] = $exp_column[0];
}
if ( $requestColumn['searchable'] == 'true' ) {
if(!empty($column['db'])){
$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
$globalSearch[] = "cast(".$column['db']." as varchar(250)) ILIKE ".$binding;
}
}
}
}
// Individual column filtering
if ( isset( $request['columns'] ) ) {
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
$requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
$column['db'] = (preg_match("/ as /i", $column['db'])) ? self::change_column($column['db']) : $column['db'];
$str = $requestColumn['search']['value'];
if ( $requestColumn['searchable'] == 'true' &&
$str != '' ) {
if(!empty($column['db'])){
$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
$columnSearch[] = "cast(".$column['db']." as varchar(250)) ILIKE ".$binding;
}
}
}
}
// Combine the filters into a single string
$where = '';
if ( count( $globalSearch ) ) {
$where = '('.implode(' OR ', $globalSearch).')';
}
if ( count( $columnSearch ) ) {
$where = $where === '' ?
implode(' AND ', $columnSearch) :
$where .' AND '. implode(' AND ', $columnSearch);
}
if ( $where !== '' ) {
$where = 'WHERE '.$where;
}
return $where;
}
/**
* Perform the SQL queries needed for an server-side processing requested,
* utilising the helper functions of this class, limit(), order() and
* filter() among others. The returned array is ready to be encoded as JSON
* in response to an SSP request, or can be modified if needed before
* sending back to the client.
*
* @param array $request Data sent to server by DataTables
* @param array|PDO $conn PDO connection resource or connection parameters array
* @param string $table SQL table to query
* @param string $primaryKey Primary key of the table
* @param array $columns Column information array
* @return array Server-side processing response array
*/
static function simple ( $request, $conn, $table, $join, $primaryKey, $columns )
{
$bindings = array();
$db = self::db( $conn );
// Build the SQL query string from the request
$limit = self::limit( $request, $columns );
$order = self::order( $request, $columns );
$where = self::filter( $request, $columns, $bindings );
// Main query to actually get the data
$data = self::sql_exec( $db, $bindings,
"SELECT ".implode(", ", self::pluck($columns, 'db'))."
FROM $table
$join
$where
$order
$limit"
);
// Data set length after filtering
$resFilterLength = self::sql_exec( $db, $bindings,
"SELECT COUNT({$primaryKey})
FROM $table
$join
$where"
);
$recordsFiltered = $resFilterLength[0][0];
// Total data set length
$resTotalLength = self::sql_exec( $db,
"SELECT COUNT({$primaryKey})
FROM $table
$join"
);
$recordsTotal = $resTotalLength[0][0];
/*
* Output
*/
return array(
"draw" => isset ( $request['draw'] ) ?
intval( $request['draw'] ) :
0,
"recordsTotal" => intval( $recordsTotal ),
"recordsFiltered" => intval( $recordsFiltered ),
"data" => self::data_output( $columns, $data )
);
}
/**
* The difference between this method and the simple one, is that you can
* apply additional where conditions to the SQL queries. These can be in
* one of two forms:
*
* * 'Result condition' - This is applied to the result set, but not the
* overall paging information query - i.e. it will not effect the number
* of records that a user sees they can have access to. This should be
* used when you want apply a filtering condition that the user has sent.
* * 'All condition' - This is applied to all queries that are made and
* reduces the number of records that the user can access. This should be
* used in conditions where you don't want the user to ever have access to
* particular records (for example, restricting by a login id).
*
* @param array $request Data sent to server by DataTables
* @param array|PDO $conn PDO connection resource or connection parameters array
* @param string $table SQL table to query
* @param string $primaryKey Primary key of the table
* @param array $columns Column information array
* @param string $whereResult WHERE condition to apply to the result set
* @param string $whereAll WHERE condition to apply to all queries
* @return array Server-side processing response array
*/
static function complex ( $request, $conn, $table, $join, $primaryKey, $columns, $whereResult=null, $whereAll=null )
{
$bindings = array();
$db = self::db( $conn );
$localWhereResult = array();
$localWhereAll = array();
$whereAllSql = '';
// Build the SQL query string from the request
$limit = self::limit( $request[0], $columns );
$order = self::order( $request[0], $columns );
$where = self::filter( $request, $columns, $bindings );
$whereResult = self::_flatten( $whereResult );
$whereAll = self::_flatten( $whereAll );
if ( $whereResult ) {
$where = $where ?
$where .' AND '.$whereResult :
'WHERE '.$whereResult;
}
if ( $whereAll ) {
$where = $where ?
$where .' AND '.$whereAll :
'WHERE '.$whereAll;
$whereAllSql = 'WHERE '.$whereAll;
}
// Main query to actually get the data
$data = self::sql_exec( $db, $bindings,
"SELECT ".implode(", ", self::pluck($columns, 'db'))."
FROM $table
$join
$where
$order
$limit"
);
// Data set length after filtering
$resFilterLength = self::sql_exec( $db, $bindings,
"SELECT COUNT({$primaryKey})
FROM $table
$join
$where"
);
$recordsFiltered = $resFilterLength[0][0];
// Total data set length
$resTotalLength = self::sql_exec( $db, $bindings,
"SELECT COUNT({$primaryKey})
FROM $table
$join".
$whereAllSql
);
$recordsTotal = $resTotalLength[0][0];
/*
* Output
*/
return array(
"draw" => isset ( $request[0]['draw'] ) ?
intval( $request[0]['draw'] ) :
0,
"recordsTotal" => intval( $recordsTotal ),
"recordsFiltered" => intval( $recordsFiltered ),
"data" => self::data_output( $columns, $data )
);
}
/**
* Connect to the database
*
* @param array $sql_details SQL server connection details array, with the
* properties:
* * host - host name
* * db - database name
* * user - user name
* * pass - user password
* @return resource Database connection handle
*/
static function sql_connect ( $sql_details )
{
try {
$db = @new PDO(
"pgsql:host={$sql_details['host']};dbname={$sql_details['db']};user={$sql_details['user']};password={$sql_details['pass']};port={$sql_details['port']};options='--client_encoding=UTF8'"
);
$db->setAttribute(PDO::ATTR_ERRMODE , PDO::ERRMODE_EXCEPTION );
}
catch (PDOException $e) {
self::fatal(
"An error occurred while connecting to the database. ".
"The error reported by the server was: ".$e->getMessage()
);
}
return $db;
}
/**
* Execute an SQL query on the database
*
* @param resource $db Database handler
* @param array $bindings Array of PDO binding values from bind() to be
* used for safely escaping strings. Note that this can be given as the
* SQL query string if no bindings are required.
* @param string $sql SQL query to execute.
* @return array Result from the query (all rows)
*/
static function sql_exec ( $db, $bindings, $sql=null )
{
// Argument shifting
if ( $sql === null ) {
$sql = $bindings;
}
$stmt = $db->prepare( $sql );
//echo $sql;
// Bind parameters
if ( is_array( $bindings ) ) {
for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) {
$binding = $bindings[$i];
$stmt->bindValue( $binding['key'], $binding['val'], $binding['type'] );
}
}
// Execute
try {
$stmt->execute();
}
catch (PDOException $e) {
self::fatal( "An SQL error occurred: ".$e->getMessage() );
}
// Return all
return $stmt->fetchAll( PDO::FETCH_BOTH );
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Internal methods
*/
/**
* Throw a fatal error.
*
* This writes out an error message in a JSON string which DataTables will
* see and show to the user in the browser.
*
* @param string $msg Message to send to the client
*/
static function fatal ( $msg )
{
echo json_encode( array(
"error" => $msg
) );
exit(0);
}
/**
* Create a PDO binding key which can be used for escaping variables safely
* when executing a query with sql_exec()
*
* @param array &$a Array of bindings
* @param * $val Value to bind
* @param int $type PDO field type
* @return string Bound key to be used in the SQL where this parameter
* would be used.
*/
static function bind ( &$a, $val, $type )
{
$key = ':binding_'.count( $a );
$a[] = array(
'key' => $key,
'val' => $val,
'type' => $type
);
return $key;
}
/**
* Pull a particular property from each assoc. array in a numeric array,
* returning and array of the property values from each item.
*
* @param array $a Array to get data from
* @param string $prop Property to read
* @return array Array of property values
*/
static function pluck ( $a, $prop )
{
$out = array();
for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
if(empty($a[$i][$prop])){
continue;
}
//removing the $out array index confuses the filter method in doing proper binding,
//adding it ensures that the array data are mapped correctly
$out[$i] = $a[$i][$prop];
}
return $out;
}
/**
* Return a string from an array or a string
*
* @param array|string $a Array to join
* @param string $join Glue for the concatenation
* @return string Joined string
*/
static function _flatten ( $a, $join = ' AND ' )
{
if ( ! $a ) {
return '';
}
else if ( $a && is_array($a) ) {
return implode( $join, $a );
}
return $a;
}
static function change_column($column_name)
{
// Spesial treatment to show row data
if (preg_match("/\./", $column_name))
{
$exp_column = explode(".", $column_name);
$column_name = end($exp_column);
}
if (preg_match("/ as /i", $column_name))
{
$exp_column = explode(" as ",$column_name);
$column_name = end($exp_column);
}
return $column_name;
}
}