fix Aiko missing
This commit is contained in:
parent
9bc2d24569
commit
1c278f92cd
26
.gitignore
vendored
Normal file
26
.gitignore
vendored
Normal file
@ -0,0 +1,26 @@
|
||||
# Aiko folder (local only)
|
||||
be/src/api/Aiko/
|
||||
|
||||
# Node modules
|
||||
node_modules/
|
||||
|
||||
# Vendor directories
|
||||
vendor/
|
||||
|
||||
# Environment files
|
||||
.env
|
||||
.env.local
|
||||
|
||||
# IDE files
|
||||
.vscode/
|
||||
.idea/
|
||||
|
||||
# OS files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Log files
|
||||
*.log
|
||||
|
||||
# Zone.Identifier files (Windows)
|
||||
*.Zone.Identifier
|
828
Aiko/Aiko/Framework/Core.php
Normal file
828
Aiko/Aiko/Framework/Core.php
Normal file
@ -0,0 +1,828 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
use Aiko\Database\Connections;
|
||||
use Aiko\Http;
|
||||
use Aiko\Token;
|
||||
use modules\rule\model\Rule;
|
||||
use Predis\Client;
|
||||
use Predis\Session\Handler;
|
||||
use Aiko\SessionRedis;
|
||||
|
||||
class Registry
|
||||
{
|
||||
private $vars = array();
|
||||
public function __set($index, $value)
|
||||
{
|
||||
$this->vars[$index] = $value;
|
||||
}
|
||||
public function __get($index)
|
||||
{
|
||||
return $this->vars[$index];
|
||||
}
|
||||
}
|
||||
|
||||
abstract class Controller
|
||||
{
|
||||
protected $registry;
|
||||
public $ActionAjaxOff;
|
||||
protected $methodAccess;
|
||||
protected $apiAction;
|
||||
protected $apiParams;
|
||||
protected $apiModule;
|
||||
protected $publicAction = array();
|
||||
private $allowJwt = array();
|
||||
protected $appID;
|
||||
protected $tokenID;
|
||||
protected $generalActions=array();
|
||||
|
||||
protected $isFile=false;
|
||||
|
||||
private $allowedMimeType = [
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/jpg',
|
||||
'video/mp4',
|
||||
'application/pdf',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheetapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'text/plain',
|
||||
'application/octet-stream',
|
||||
'application/zip',
|
||||
'application/msword',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
|
||||
'application/vnd.ms-word.document.macroEnabled.12',
|
||||
'application/vnd.ms-word.template.macroEnabled.12',
|
||||
'application/vnd.ms-excel',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
|
||||
'application/vnd.ms-excel.sheet.macroEnabled.12',
|
||||
'application/vnd.ms-excel.template.macroEnabled.12',
|
||||
'application/vnd.ms-excel.addin.macroEnabled.12',
|
||||
'application/vnd.ms-excel.sheet.binary.macroEnabled.12'
|
||||
];
|
||||
|
||||
public function __construct($registry)
|
||||
{
|
||||
// session_id('hcportal-session-id');
|
||||
// session_start();
|
||||
// Http::enabledCors();
|
||||
|
||||
$this->registry = $registry;
|
||||
$this->methodAccess = $_SERVER['REQUEST_METHOD'];
|
||||
$this->allowJwt = array('dologin', 'dologout', 'refreshToken', 'generateNewToken', 'loginauth');
|
||||
|
||||
|
||||
// connect main DB
|
||||
// $this->registry = $registry;
|
||||
// $this->registry->db = Connections::getInstance(
|
||||
// $this->registry->config->host,
|
||||
// $this->registry->config->db,
|
||||
// $this->registry->config->socket,
|
||||
// $this->registry->config->user,
|
||||
// $this->registry->config->password,
|
||||
// $this->registry->config->dbms
|
||||
// );
|
||||
|
||||
if($this->registry->config->dbMainConType!=='local')
|
||||
{
|
||||
$this->registry->db = Connections::getInstance($this->registry->config->dbMainConType);
|
||||
}else {
|
||||
$this->registry->db = Connections::getInstance(
|
||||
$this->registry->config->dbMainConType,
|
||||
$this->registry->config->host,
|
||||
$this->registry->config->socket,
|
||||
$this->registry->config->user,
|
||||
$this->registry->config->password
|
||||
);
|
||||
}
|
||||
|
||||
// $handler = new Session($registry);
|
||||
// $result= session_set_save_handler($handler,true);
|
||||
|
||||
// session_start();
|
||||
// session_start();
|
||||
|
||||
|
||||
// if (!interface_exists('SessionHandlerInterface')) {
|
||||
// exit('ATTENTION: the session handler implemented by Predis requires PHP >= 5.4.0 ' .
|
||||
// "or a polyfill for SessionHandlerInterface provided by an external package.\n");
|
||||
// }
|
||||
// $single_server=[
|
||||
// 'scheme' => 'tcp',
|
||||
// 'host' => '10.1.200.218',
|
||||
// 'port' => 6388,
|
||||
// ];
|
||||
// $client = new Client($single_server, ['prefix' => 'sessions:']);
|
||||
|
||||
// // Set `gc_maxlifetime` to specify a time-to-live of 5 seconds for session keys.
|
||||
// $handler = new Handler($client, ['gc_maxlifetime' => get_cfg_var("session.gc_maxlifetime")]);
|
||||
|
||||
// // Register the session handler.
|
||||
// $handler->register();
|
||||
|
||||
// // We just set a fixed session ID only for the sake of our example.
|
||||
// session_id('hcportalsessionid');
|
||||
|
||||
if(!isset($_SESSION))
|
||||
{
|
||||
session_start();
|
||||
}
|
||||
// check mime_type
|
||||
$this->checkContentFile();
|
||||
|
||||
|
||||
}
|
||||
|
||||
abstract public function index();
|
||||
|
||||
protected function checkToken()
|
||||
{
|
||||
try {
|
||||
$token = Http::getTokenJWT();
|
||||
|
||||
// get token ID
|
||||
$tokenPart = explode('.', $token);
|
||||
|
||||
if (count($tokenPart) != 4) {
|
||||
throw new \ErrorException('token part invalid');
|
||||
}
|
||||
|
||||
$stmt = $this->registry->db->prepare('select appID,tokenID,chipper,data,expired from jwt where id=:id');
|
||||
$stmt->bindValue(':id', $tokenPart[3], \PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
$rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
|
||||
|
||||
if (count($rs) == 0) {
|
||||
throw new \ErrorException('token jwt not exist');
|
||||
}
|
||||
|
||||
$this->appID=$rs[0]['appID'];
|
||||
$this->tokenID=$rs[0]['tokenID'];
|
||||
|
||||
$now = time();
|
||||
if ($rs[0]['expired'] < $now) {
|
||||
throw new \Exception('Time Token refresh Exceded');
|
||||
}
|
||||
|
||||
// update expired
|
||||
$stmt = $this->registry->db->prepare('update jwt set expired=:expired where id=:id');
|
||||
$stmt->bindValue(':id', $tokenPart[3], \PDO::PARAM_INT);
|
||||
$stmt->bindValue(':expired', time() + __LIFETIMEJWT, \PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
|
||||
$newToken = $tokenPart[0] . '.' . $tokenPart[1] . '.' . $tokenPart[2];
|
||||
|
||||
$data = Token::decodeJWTNew($newToken, $rs[0]['chipper']);
|
||||
if (is_numeric($data)) {
|
||||
if ($data === 8) // expired token
|
||||
{
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token : expired token , token :' . $data);
|
||||
Http::tokenExpired(array('message' => 'Token need refresh'));
|
||||
} else {
|
||||
throw new \ErrorException('decode Error token :' . $data);
|
||||
}
|
||||
}
|
||||
$rData = json_decode(json_encode($data->data), true);
|
||||
\Helper::setSession($rData);
|
||||
return true;
|
||||
} catch (\ErrorException $e) {
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token :' . $e->getMessage());
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Wrong Token'));
|
||||
//return false;
|
||||
} catch (\Exception $e) {
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token :' . $e->getMessage());
|
||||
Http::UnauthorizedResponseJson(array('message' => $e->getMessage()));
|
||||
} catch (\PDOException $e) {
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token :' . $e->getMessage());
|
||||
Http::UnauthorizedResponseJson(array('message' => 'query error '));
|
||||
}
|
||||
}
|
||||
protected function checkTokenOld()
|
||||
{
|
||||
try {
|
||||
$token = Http::getTokenJWT();
|
||||
|
||||
|
||||
|
||||
$data = Token::decodeJWTNew($token);
|
||||
if (is_numeric($data)) {
|
||||
if ($data === 8) // expired token
|
||||
{
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token : expired token , token :' . $data);
|
||||
Http::tokenExpired(array('message' => 'Wrong Token'));
|
||||
} else {
|
||||
throw new \ErrorException('decode Error token :' . $data);
|
||||
}
|
||||
}
|
||||
$rData = json_decode(json_encode($data->data), true);
|
||||
\Helper::setSession($rData);
|
||||
return true;
|
||||
} catch (\ErrorException $e) {
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token :' . $e->getMessage());
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Wrong Token'));
|
||||
//return false;
|
||||
} catch (\Exception $e) {
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token :' . $e->getMessage());
|
||||
Http::UnauthorizedResponseJson(array('message' => $e->getMessage()));
|
||||
} catch (\PDOException $e) {
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token :' . $e->getMessage());
|
||||
Http::UnauthorizedResponseJson(array('message' => 'query error '));
|
||||
}
|
||||
}
|
||||
|
||||
protected function checkRulesAccess()
|
||||
{
|
||||
$rule = new Rule($this->registry);
|
||||
if (!in_array($this->apiAction, $this->publicAction)) {
|
||||
$hasAccess = $rule->hasAccess($this->apiModule, $this->apiAction);
|
||||
|
||||
if ($hasAccess == false) {
|
||||
Http::ErrorQueryResponse('operation not permit', 'json');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected function checkAPIAccess()
|
||||
{
|
||||
|
||||
/* check method access */
|
||||
$this->allowOptionMethod();
|
||||
|
||||
if (!in_array($this->methodAccess, array('POST', 'GET', 'DELETE'))) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Method Not allowed'));
|
||||
}
|
||||
$this->apiAction = '';
|
||||
switch ($this->methodAccess) {
|
||||
case 'POST':
|
||||
/* check and get action */
|
||||
$this->apiAction = Http::GetvarData('action');
|
||||
if (!isset($this->apiAction)) {
|
||||
$jtext = Http::GetBodyRequest();
|
||||
$this->apiParams = \Firebase\JWT\JWT::jsonDecode($jtext);
|
||||
if (!isset($this->apiParams->action)) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Action not set'));
|
||||
}
|
||||
$this->apiAction = $this->apiParams->action;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
// GET // DELETE
|
||||
$this->apiAction = Http::GetvarData('action');
|
||||
if (strlen($this->apiAction) === 0) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Action not set'));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
/* check token */
|
||||
$isAllowed = $this->checkToken();
|
||||
if (!$isAllowed) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Wrong Token'));
|
||||
}
|
||||
|
||||
/* check rule */
|
||||
$this->checkRulesAccess();
|
||||
}
|
||||
|
||||
protected function isAuthorized()
|
||||
{
|
||||
/* check method access */
|
||||
$this->allowOptionMethod();
|
||||
|
||||
if (!in_array($this->methodAccess, array('POST', 'GET', 'DELETE'))) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Method Not allowed'));
|
||||
}
|
||||
$this->apiAction = '';
|
||||
|
||||
switch ($this->methodAccess) {
|
||||
case 'POST':
|
||||
/* check and get action */
|
||||
if($this->isFile){
|
||||
$aText['action']=Http::GetVarData('action','post');
|
||||
$this->apiParams=\Firebase\JWT\JWT::jsonDecode(\Firebase\JWT\JWT::jsonEncode($aText));
|
||||
$this->apiAction = Http::GetVarData('action','post');
|
||||
}else{
|
||||
$jtext = Http::GetBodyRequest();
|
||||
$this->apiParams = \Firebase\JWT\JWT::jsonDecode($jtext);
|
||||
|
||||
if (!isset($this->apiParams->action)) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Action not set'));
|
||||
}
|
||||
|
||||
$this->apiAction = $this->apiParams->action;
|
||||
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
// GET // DELETE
|
||||
$this->apiAction = Http::GetvarData('action');
|
||||
$this->apiParams = json_decode(json_encode(Http::getAllRequest()));
|
||||
if (strlen($this->apiAction) === 0) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Action not set'));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if (!in_array($this->apiAction, $this->allowJwt)) {
|
||||
/* check token */
|
||||
$isAllowed = $this->checkToken();
|
||||
if (!$isAllowed) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Wrong Token'));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (is_array($this->generalActions)) {
|
||||
/* check rule */
|
||||
if(!in_array($this->apiAction,$this->generalActions)){
|
||||
$this->checkRulesAccess();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* process request */
|
||||
$this->prosesRequest();
|
||||
}
|
||||
|
||||
protected function checkAPIAccessEvaluation()
|
||||
{
|
||||
if ($this->methodAccess == 'OPTIONS') {
|
||||
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
|
||||
Http::ResponseJson('ok', '0', '1');
|
||||
}
|
||||
}
|
||||
$isAllowed = $this->checkTokenEvaluation();
|
||||
if (!$isAllowed) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Wrong Token'));
|
||||
}
|
||||
}
|
||||
|
||||
protected function checkTokenEvaluation()
|
||||
{
|
||||
try {
|
||||
|
||||
$token = Http::getTokenJWT();
|
||||
$data = Token::decodeJWT($token);
|
||||
if (!isset($data->data)) {
|
||||
throw new \ErrorException('decode Error token :' . $token);
|
||||
}
|
||||
|
||||
$_SESSION = array();
|
||||
session_destroy();
|
||||
|
||||
$_SESSION['group'] = $data->data->group;
|
||||
$_SESSION['username'] = $data->data->username;
|
||||
$_SESSION['name'] = isset($data->data->name) ? $data->data->name : $data->data->nama;
|
||||
$_SESSION['section'] = isset($data->data->section) ? $data->data->section : $data->data->secion;
|
||||
$_SESSION['userID'] = $data->data->userID;
|
||||
$_SESSION['empNo'] = isset($data->data->empNo) ? $data->data->empNo : '';
|
||||
$_SESSION['empSite'] = $data->data->empSite;
|
||||
$_SESSION['empSubArea'] = isset($data->data->empSubArea) ? $data->data->empSubArea : '';
|
||||
$_SESSION['flagApp'] = isset($data->data->flagApp) ? $data->data->flagApp : '';
|
||||
$_SESSION['nationality'] = isset($data->data->nationality) ? $data->data->nationality : '';
|
||||
$_SESSION['role'] = isset($data->data->role) ? $data->data->role : '';
|
||||
|
||||
// if jwt valid set session var
|
||||
|
||||
return true;
|
||||
} catch (\ErrorException $e) {
|
||||
$this->registry->log->error('Module Controller / check Token Eval :' . $e->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
protected function allowOptionMethod()
|
||||
{
|
||||
if ($this->methodAccess == 'OPTIONS') {
|
||||
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
|
||||
Http::ResponseJson(array('ok'), '0', '1');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function prosesRequest()
|
||||
{
|
||||
switch ($this->methodAccess) {
|
||||
case 'POST':
|
||||
$this->executePost();
|
||||
break;
|
||||
case 'GET':
|
||||
$this->executeGet();
|
||||
break;
|
||||
case 'DELETE':
|
||||
$this->executeDelete();
|
||||
break;
|
||||
default:
|
||||
Http::ErrorQueryResponse('method not permit');
|
||||
break;
|
||||
}
|
||||
}
|
||||
protected function executePost()
|
||||
{
|
||||
$act = $this->apiAction;
|
||||
if (method_exists($this, $act)) {
|
||||
$this->$act();
|
||||
} else {
|
||||
Http::ErrorQueryResponse('Action not registered');
|
||||
}
|
||||
}
|
||||
private function executeGet()
|
||||
{
|
||||
$act = $this->apiAction;
|
||||
if (method_exists($this, $act)) {
|
||||
$this->$act();
|
||||
} else {
|
||||
Http::ErrorQueryResponse('Action not registered');
|
||||
}
|
||||
}
|
||||
protected function executeDelete()
|
||||
{
|
||||
}
|
||||
|
||||
protected function extendAllowJwt(array $extended)
|
||||
{
|
||||
foreach ($extended as $value) {
|
||||
array_push($this->allowJwt, $value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* fungsi ini untuk convert message dari api.
|
||||
* untuk keperluan migrasi FE ke framework yang baru
|
||||
* karena fokus utama migrasi FE dulu jadi BE yang menyesuaikan
|
||||
*
|
||||
* @param message
|
||||
* @return $result : string
|
||||
*/
|
||||
protected function convertMessages($message)
|
||||
{
|
||||
$result = $message;
|
||||
switch($message){
|
||||
case 'PAYROLL.MESSAGE.SUCCMESINS':
|
||||
$result = 'MESSAGE.SUCCMESINS';
|
||||
break;
|
||||
case 'PAYROLL.MESSAGE.FAILMESEXIST':
|
||||
$result = 'MESSAGE.DATA_ALREADY_EXIST';
|
||||
break;
|
||||
case 'PAYROLL.MESSAGE.FAILMESUNKNOWN':
|
||||
$result = 'MESSAGE.FAILMESUNKNOWN';
|
||||
break;
|
||||
case 'PAYROLL.MESSAGE.FAILMESERRREQ':
|
||||
$result = 'MESSAGE.FAILMESERRREQ';
|
||||
break;
|
||||
case 'PAYROLL.MESSAGE.SUCCMESDEL':
|
||||
$result = 'MESSAGE.SUCCMESDEL';
|
||||
break;
|
||||
case 'PAYROLL.MESSAGE.SUCCMESUPD':
|
||||
$result = 'MESSAGE.SUCCMESUPD';
|
||||
break;
|
||||
case 'PAYROLL.MESSAGE.FAILMESQUERY':
|
||||
$result = 'MESSAGE.FAILMESQUERY';
|
||||
break;
|
||||
case 'MENU.MASTER_DATA.ADMINISTRATIVE_AREA.MAIN.CANTDELETE':
|
||||
$result = 'MESSAGE.CANTDELETE';
|
||||
break;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* fungsi ini untuk convert response menjadi format pagination.
|
||||
* untuk keperluan migrasi FE ke framework yang baru
|
||||
* karena fokus utama migrasi FE dulu jadi BE yang menyesuaikan
|
||||
*
|
||||
* @param array
|
||||
* @return array
|
||||
*/
|
||||
protected function convertToPaginationFormat($array)
|
||||
{
|
||||
$total = count($array);
|
||||
$aData['iTotalDisplayRecords'] = $total;
|
||||
$aData['iTotalRecords'] = $total;
|
||||
$aData['aData'] = $array;
|
||||
|
||||
return $aData;
|
||||
}
|
||||
|
||||
private function checkContentFile(){
|
||||
$this->isFile=Http::isMultipartFormData();
|
||||
if($this->isFile){
|
||||
if (!empty($_FILES) && is_array($_FILES) && count($_FILES) > 0) {
|
||||
foreach ($_FILES as $file) {
|
||||
$filepath = $file['tmp_name'];
|
||||
// $filesize = filesize($filepath);
|
||||
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
|
||||
$filetype = finfo_file($fileinfo, $filepath);
|
||||
finfo_close($fileinfo);
|
||||
if (!in_array($filetype, $this->allowedMimeType)) {
|
||||
Http::ErrorQueryResponse(array('name' => $file['name'], 'message' =>'15220-failed'), 'json');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected function setSession($token)
|
||||
{
|
||||
// get token ID
|
||||
$tokenPart = explode('.', $token);
|
||||
\Helper::dump($tokenPart);
|
||||
if (count($tokenPart) != 4) {
|
||||
throw new \ErrorException('token part invalid');
|
||||
}
|
||||
|
||||
$stmt = $this->registry->db->prepare('select appID,tokenID,chipper,data,expired from jwt where id=:id');
|
||||
$stmt->bindValue(':id', $tokenPart[3], \PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
$rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
|
||||
|
||||
if (count($rs) == 0) {
|
||||
throw new \ErrorException('token jwt not exist');
|
||||
}
|
||||
|
||||
$this->appID=$rs[0]['appID'];
|
||||
$this->tokenID=$rs[0]['tokenID'];
|
||||
|
||||
$now = time();
|
||||
if ($rs[0]['expired'] < $now) {
|
||||
throw new \Exception('Time Token refresh Exceded');
|
||||
}
|
||||
|
||||
// update expired
|
||||
$stmt = $this->registry->db->prepare('update jwt set expired=:expired where id=:id');
|
||||
$stmt->bindValue(':id', $tokenPart[3], \PDO::PARAM_INT);
|
||||
$stmt->bindValue(':expired', time() + __LIFETIMEJWT, \PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
|
||||
$newToken = $tokenPart[0] . '.' . $tokenPart[1] . '.' . $tokenPart[2];
|
||||
|
||||
$data = Token::decodeJWTNew($newToken, $rs[0]['chipper']);
|
||||
if (is_numeric($data)) {
|
||||
if ($data === 8) // expired token
|
||||
{
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token : expired token , token :' . $data);
|
||||
Http::tokenExpired(array('message' => 'Token need refresh'));
|
||||
} else {
|
||||
throw new \ErrorException('decode Error token :' . $data);
|
||||
}
|
||||
}
|
||||
$rData = json_decode(json_encode($data->data), true);
|
||||
\Helper::setSession($rData);
|
||||
}
|
||||
}
|
||||
|
||||
class Router
|
||||
{
|
||||
private $registry;
|
||||
private $path;
|
||||
private $args = array();
|
||||
public $file;
|
||||
public $controller;
|
||||
public $action;
|
||||
public $parts;
|
||||
private $controllerPath;
|
||||
|
||||
private $prefix;
|
||||
public function __construct($registry,$prefix='')
|
||||
{
|
||||
$this->registry = $registry;
|
||||
$this->prefix=$prefix;
|
||||
}
|
||||
|
||||
public function loader()
|
||||
{
|
||||
|
||||
try {
|
||||
/*** a new controller class instance , pembuatan controller object***/
|
||||
$class = $this->controller;
|
||||
$this->registry->controller = $class;
|
||||
$this->registry->action = $this->action;
|
||||
$ClassName = ucfirst($class);
|
||||
$mod = strtolower($class);
|
||||
|
||||
$aModules = explode('/', $this->controllerPath);
|
||||
$jumModules = count($aModules);
|
||||
//$mod1 = substr($this->controllerPath, 1);
|
||||
$mod1 = $this->controllerPath;
|
||||
$strslash = substr($this->controllerPath, 0, 1);
|
||||
if ($strslash == '/' || $strslash == '\\') {
|
||||
$mod1 = substr($this->controllerPath, 1);
|
||||
}
|
||||
|
||||
$newmod = str_replace('/', '\\', $mod1);
|
||||
|
||||
$namespaces = "\\modules\\{$newmod}\\controller\\{$ClassName}Controller";
|
||||
|
||||
$this->registry->ContPath = $mod1;
|
||||
|
||||
$controller = new $namespaces($this->registry);
|
||||
|
||||
/*** check if the action is callable ***/
|
||||
if (is_callable(array($controller, $this->action)) == false) {
|
||||
|
||||
$action = 'index';
|
||||
} else {
|
||||
$action = $this->action;
|
||||
}
|
||||
|
||||
/*** run the action , ini sama kayak execute function yang ada pada controller pada mvc sebelumnya
|
||||
* ***/
|
||||
if ($this->registry->config->ajax == 'on') {
|
||||
if (!empty($controller->ActionAjaxOff)) {
|
||||
if (!in_array($action, $controller->ActionAjaxOff)) {
|
||||
// if true
|
||||
|
||||
if (!$this->registry->isAjax) {
|
||||
exit('ajax request required');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!$this->registry->isAjax) {
|
||||
exit('ajax request required');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if ($this->registry->isAjax) {
|
||||
exit('please set ajax config to "on" if request ajax required');
|
||||
}
|
||||
}
|
||||
$controller->$action();
|
||||
} catch (\Exception $e) {
|
||||
$this->registry->log->error('Core / Loader :' . $e->getMessage() . ' Line :' . $e->getLine() . ' ' . $e->getFile());
|
||||
Http::InternalServerError('error loader');
|
||||
}
|
||||
}
|
||||
|
||||
private function getController()
|
||||
{
|
||||
|
||||
try {
|
||||
/* get variable*/
|
||||
$this->controller = $this->getControllerName();
|
||||
$j = 0;
|
||||
if (!(empty($this->parts[2]) or $this->parts[2] == '-')) {
|
||||
for ($i = 2; $i < count($this->parts); $i++) {
|
||||
$this->args[$j] = $this->parts[$i];
|
||||
$j++;
|
||||
}
|
||||
$this->registry->vars = $this->args;
|
||||
} else {
|
||||
$this->registry->vars = 'null';
|
||||
}
|
||||
|
||||
/*** set the file path ***/
|
||||
return $this->controller;
|
||||
} catch (\Exception $e) {
|
||||
|
||||
$this->registry->log->error('Core / Loader :' . $e->getMessage() . ' Line :' . $e->getLine() . ' ' . $e->getFile());
|
||||
\Aiko\Http::InternalServerError('Error loader');
|
||||
}
|
||||
}
|
||||
public function getControllerName()
|
||||
{
|
||||
|
||||
try {
|
||||
$restrict = '';
|
||||
if ($this->registry->config->restrict == 'yes') {
|
||||
if (isset($this->registry->config->ipconfig)) {
|
||||
$ip = $this->getRealIpAddr();
|
||||
$register = in_array($ip, $this->registry->config->ipconfig);
|
||||
|
||||
if ($ip != '127.0.0.1') {
|
||||
if (!$register) {
|
||||
$restrict = 'restrict';
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$restrict = 'restrict';
|
||||
}
|
||||
}
|
||||
$this->getName($restrict);
|
||||
$this->Request_check();
|
||||
|
||||
return $this->controller;
|
||||
} catch (\Exception $e) {
|
||||
|
||||
$this->registry->log->error('Core / Loader :' . $e->getMessage() . ' Line :' . $e->getLine());
|
||||
\Aiko\Http::InternalServerError('Error loader');
|
||||
}
|
||||
}
|
||||
|
||||
private function getName($restrict)
|
||||
{
|
||||
try {
|
||||
if ($restrict == 'restrict') {
|
||||
$this->controller = 'restrict';
|
||||
$this->controllerPath = 'restrict';
|
||||
} else {
|
||||
$route = (empty($_GET['rt'])) ? '' : $_GET['rt'];
|
||||
if (empty($route)) {
|
||||
// jika route tidak ada / pada awal page
|
||||
$route = 'index';
|
||||
} else {
|
||||
// clean root with prefix
|
||||
$route= $this->cleanRoute($route);
|
||||
/*** get the parts of the route ***/
|
||||
$this->parts = explode('/', $route);
|
||||
// set controller name
|
||||
// cek apakan part yang pertama memiliki controller kalau tidak ditemukan return 404
|
||||
if (!is_dir(__SITE_PATH . '/src/modules/' . $this->parts[0])) {
|
||||
$this->controller = 'error404';
|
||||
$this->controllerPath = 'error404';
|
||||
} else {
|
||||
$i = 0;
|
||||
$path = '';
|
||||
$found = false;
|
||||
do {
|
||||
$path .= '/' . $this->parts[$i];
|
||||
$dir = __SITE_PATH . '/src/modules' . $path;
|
||||
if (file_exists($dir . '/controller')) {
|
||||
$found = true;
|
||||
break;
|
||||
}
|
||||
$i++;
|
||||
} while ($i < count($this->parts));
|
||||
if ($found) {
|
||||
$this->controller = $this->parts[$i];
|
||||
$this->controllerPath = $path;
|
||||
} else {
|
||||
$this->controller = 'error404';
|
||||
$this->controllerPath = 'error404';
|
||||
}
|
||||
|
||||
if (isset($this->parts[$i + 1])) {
|
||||
// set action name
|
||||
$this->action = $this->parts[$i + 1];
|
||||
}
|
||||
}
|
||||
}
|
||||
// cek apakah controller kosong, jika kosong set ke index
|
||||
if (empty($this->controller)) {
|
||||
$this->controller = 'index';
|
||||
$this->controllerPath = 'index';
|
||||
}
|
||||
|
||||
/*** Get action ***/
|
||||
if (empty($this->action)) {
|
||||
$this->action = 'index';
|
||||
}
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
|
||||
$this->registry->log->error('Core / Loader :' . $e->getMessage() . ' Line :' . $e->getLine());
|
||||
\Aiko\Http::InternalServerError('Error loader');
|
||||
}
|
||||
}
|
||||
private function Request_check()
|
||||
{
|
||||
$this->registry->isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) and
|
||||
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
|
||||
}
|
||||
public function getControllerPath()
|
||||
{
|
||||
return $this->controllerPath;
|
||||
}
|
||||
private function getRealIpAddr()
|
||||
{
|
||||
if (!empty($_SERVER['HTTP_CLIENT_IP'])) { //check ip from share internet
|
||||
$ip = $_SERVER['HTTP_CLIENT_IP'];
|
||||
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { //to check ip is pass from proxy
|
||||
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
|
||||
} else {
|
||||
$ip = $_SERVER['REMOTE_ADDR'];
|
||||
}
|
||||
return $ip;
|
||||
}
|
||||
|
||||
private function cleanRoute($route):string{
|
||||
$prefixLength=strlen($this->prefix);
|
||||
if ($prefixLength==0){
|
||||
return $route;
|
||||
}
|
||||
$routePrefix=substr($route,0,$prefixLength);
|
||||
if($this->prefix!==$routePrefix){
|
||||
|
||||
Http::InternalServerError('failed route');
|
||||
}
|
||||
$newRoute= substr($route,$prefixLength);
|
||||
if(strlen($newRoute)==0 || $newRoute=='/'){
|
||||
$newRoute='index';
|
||||
}
|
||||
|
||||
// check apakah string pertama route / ?
|
||||
if(substr($newRoute,0,1)=='/'){
|
||||
$newRoute=substr($newRoute,1);
|
||||
}
|
||||
return $newRoute;
|
||||
}
|
||||
|
||||
}
|
3
Aiko/Aiko/Framework/Core.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Framework/Core.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
184
Aiko/Aiko/Framework/Database.php
Normal file
184
Aiko/Aiko/Framework/Database.php
Normal file
@ -0,0 +1,184 @@
|
||||
<?php
|
||||
namespace Aiko\Database;
|
||||
|
||||
include __SITE_PATH . '/Aiko/Includes/db.config.php';
|
||||
|
||||
use PDO;
|
||||
use PDOException;
|
||||
|
||||
|
||||
class Connections
|
||||
{
|
||||
private static $instance = null;
|
||||
private static $instancePMA = NULL;
|
||||
private static $instanceCartal=NULL;
|
||||
private static $scada=NULL;
|
||||
|
||||
private function __construct()
|
||||
{}
|
||||
|
||||
public static function getInstance(
|
||||
$type,
|
||||
$host='127.0.0.1',
|
||||
$socket= '/var/lib/mysql/mysql.sock',
|
||||
$user='root',
|
||||
$password='')
|
||||
{
|
||||
$aHost=array('127.0.0.1','localhost');
|
||||
if(in_array($host,$aHost))
|
||||
{
|
||||
$host = $host;
|
||||
}else {
|
||||
$host='1.1.1.1';
|
||||
}
|
||||
|
||||
$db = $db = 'hcportal_local';
|
||||
$socket = $socket;
|
||||
$user = $user;
|
||||
$pass = $password;
|
||||
if($type!=='local'){
|
||||
$config = getConfig($type);
|
||||
$host = $config['host'];
|
||||
$db = $config['db'];
|
||||
$socket = $config['socket'];
|
||||
$user = $config['user'];
|
||||
$pass = $config['password'];
|
||||
}
|
||||
|
||||
|
||||
if (!self::$instance) {
|
||||
try
|
||||
{
|
||||
switch ($config['dbms']) {
|
||||
case 'mysql':
|
||||
// self::$instance = new PDO("mysql:host=$host;dbname=$db;unix_socket=$socket;port=4867;", "$user","$pass");
|
||||
self::$instance = new PDO("mysql:host=$host;dbname=$db;unix_socket=$socket;", "$user", "$pass");
|
||||
break;
|
||||
case 'oracle':
|
||||
self::$instance = new PDO("oci:host=$host;dbname=$db;", "$user", "$pass");
|
||||
break;
|
||||
case 'pgsql':
|
||||
self::$instance = new PDO("pgsql:host=$host;dbname=$db;", "$user", "$pass");
|
||||
break;
|
||||
case 'sqlite':
|
||||
break;
|
||||
self::$instance = new PDO("sqlite:$db;");
|
||||
|
||||
}
|
||||
self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
self::$instance->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
|
||||
// self::$instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
|
||||
|
||||
return self::$instance;
|
||||
} catch (PDOException $e) {
|
||||
self::showerror("Sorry, an error has occured. Please try your request \n" . $e->getMessage());
|
||||
die();
|
||||
}
|
||||
} else {
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static function getInstancePMA() {
|
||||
$config = getConfig('pma');
|
||||
$host = $config['host'];
|
||||
$db = $config['db'];
|
||||
$socket = $config['socket'];
|
||||
$user = $config['user'];
|
||||
$pass = $config['password'];
|
||||
if (!self::$instancePMA)
|
||||
{
|
||||
try
|
||||
{
|
||||
self::$instancePMA = new PDO("mysql:host=$host;dbname=$db;unix_socket=$socket;", "$user","$pass");
|
||||
self::$instancePMA-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
self::$instancePMA->setAttribute(PDO::ATTR_CASE,PDO::CASE_NATURAL);
|
||||
return self::$instancePMA;
|
||||
}catch (PDOException $e)
|
||||
{
|
||||
self::showerror("Sorry, an error has occured. Please try your request \n".$e->getMessage());
|
||||
die();
|
||||
}
|
||||
}else
|
||||
{
|
||||
return self::$instancePMA;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static function getInstanceCartal($type) {
|
||||
$config = getConfig($type);
|
||||
$host = $config['host'];
|
||||
$db = $config['db'];
|
||||
$socket = $config['socket'];
|
||||
$user = $config['user'];
|
||||
$pass = $config['password'];
|
||||
if (!self::$instanceCartal)
|
||||
{
|
||||
try
|
||||
{
|
||||
self::$instanceCartal = new PDO("mysql:host=$host;dbname=$db;unix_socket=$socket;", "$user","$pass");
|
||||
self::$instanceCartal-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
self::$instanceCartal->setAttribute(PDO::ATTR_CASE,PDO::CASE_NATURAL);
|
||||
return self::$instanceCartal;
|
||||
}catch (PDOException $e)
|
||||
{
|
||||
self::showerror("Sorry, an error has occured. Please try your request \n".$e->getMessage());
|
||||
die();
|
||||
}
|
||||
}else
|
||||
{
|
||||
return self::$instanceCartal;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static function getInstanceSCADA($type) {
|
||||
$config = getConfig($type);
|
||||
$host = $config['host'];
|
||||
$db = $config['db'];
|
||||
$user = $config['user'];
|
||||
$pass = $config['password'];
|
||||
$port = $config['port'];
|
||||
if (!self::$scada)
|
||||
{
|
||||
try
|
||||
{
|
||||
self::$scada = new PDO("pgsql:host=$host;port=$port;dbname=$db;", "$user", "$pass");
|
||||
self::$scada-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
self::$scada->setAttribute(PDO::ATTR_CASE,PDO::CASE_NATURAL);
|
||||
return self::$scada;
|
||||
}catch (PDOException $e)
|
||||
{
|
||||
self::showerror("Sorry, an error has occured. Please try your request \n".$e->getMessage());
|
||||
die();
|
||||
}
|
||||
}else
|
||||
{
|
||||
return self::$instanceCartal;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static function exceptionHandler($e)
|
||||
{
|
||||
set_exception_handler('exceptionHandler');
|
||||
self::showerror("Sorry, the site under maintenance \n");
|
||||
}
|
||||
public static function showerror($m)
|
||||
{
|
||||
echo "<h2>Error</h2>";
|
||||
echo nl2br(htmlspecialchars($m));
|
||||
}
|
||||
/**
|
||||
*
|
||||
*
|
||||
* Like the constructor, we make __clone private
|
||||
* so nobody can clone the instance
|
||||
*
|
||||
*/
|
||||
private function __clone()
|
||||
{}
|
||||
|
||||
}
|
3
Aiko/Aiko/Framework/Database.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Framework/Database.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
11
Aiko/Aiko/Framework/Error.php
Normal file
11
Aiko/Aiko/Framework/Error.php
Normal file
@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
function exception_error_handler($severity, $message, $file, $line)
|
||||
{
|
||||
if (!(error_reporting() & $severity)) {
|
||||
// This error code is not included in error_reporting
|
||||
return;
|
||||
}
|
||||
throw new ErrorException($message, 0, $severity, $file, $line);
|
||||
}
|
||||
set_error_handler('exception_error_handler', E_ALL);
|
3
Aiko/Aiko/Framework/Error.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Framework/Error.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
126
Aiko/Aiko/Framework/Init.php
Normal file
126
Aiko/Aiko/Framework/Init.php
Normal file
@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
|
||||
TODO:
|
||||
- untuk sementara include manual di sini nanti akan di pindahkan ke composer
|
||||
- Second todo item
|
||||
|
||||
*/
|
||||
|
||||
/**setup secret constant */
|
||||
define('__PAYROLLCODE__', '123456');
|
||||
|
||||
define('__CODE_COST', '123456');
|
||||
|
||||
define('__CODE_PKWT_LOA', '123456');
|
||||
|
||||
define('__ENCRYPT_METHOD', 'AES-256-CBC');
|
||||
|
||||
define('__SECRET_KEY', 'suh3ndr441k041l4');
|
||||
|
||||
define('__SECRET_IV', 'suh3ndr441k041l4');
|
||||
|
||||
|
||||
/** include framework files */
|
||||
|
||||
include __SITE_PATH . '/Aiko/Includes/App.config.php';
|
||||
|
||||
include __SITE_PATH . '/Aiko/Framework/Error.php';
|
||||
|
||||
include __SITE_PATH . '/Aiko/Framework/Database.php';
|
||||
|
||||
include __SITE_PATH . '/Aiko/Framework/Model.php';
|
||||
|
||||
include __SITE_PATH . '/Aiko/Framework/Template.php';
|
||||
|
||||
include __SITE_PATH . '/Aiko/Framework/Token.php';
|
||||
|
||||
include __SITE_PATH . '/Aiko/Includes/config.php';
|
||||
|
||||
/** end include framework files */
|
||||
|
||||
|
||||
/*
|
||||
* create object registry
|
||||
*/
|
||||
$registry = new \Aiko\Registry();
|
||||
|
||||
/*
|
||||
* load variable config to registry
|
||||
*/
|
||||
|
||||
|
||||
$registry->config = json_decode(json_encode($config));
|
||||
|
||||
//$registry->config = json_decode(json_encode(parse_ini_file(__SITE_PATH . '/includes/' . 'config.ini')));
|
||||
|
||||
|
||||
// var_dump($registry->config);
|
||||
|
||||
/*
|
||||
* set server address dari file config
|
||||
*/
|
||||
define('__SERVERADDR', $registry->config->server_address);
|
||||
|
||||
/*
|
||||
* set time zone area application
|
||||
*/
|
||||
date_default_timezone_set($registry->config->time_zone);
|
||||
|
||||
/*
|
||||
Create object registry for carry object
|
||||
*/
|
||||
|
||||
$registry->router = new Aiko\Router($registry);
|
||||
|
||||
/*
|
||||
Set Controller Name
|
||||
*/
|
||||
|
||||
$registry->controller = $registry->router->getControllerName();
|
||||
|
||||
/*
|
||||
Create object template
|
||||
*/
|
||||
|
||||
$registry->template = new \Aiko\Template\Template($registry);
|
||||
|
||||
/*
|
||||
Set Debugging
|
||||
*/
|
||||
/*set Aiko Debugging on developer mode*/
|
||||
|
||||
$registry->ab = new \Aiko\Debug($registry->config->environment);
|
||||
|
||||
/* set log aplikasi */
|
||||
$registry->log = new \Aiko\Log($registry->config->log);
|
||||
|
||||
|
||||
//$this->registry = $registry;
|
||||
//$sessionHandler = new \Aiko\Session($registry);
|
||||
// session_set_save_handler($sessionHandler, true);
|
||||
// session_set_save_handler(
|
||||
// array($sessionHandler, 'open'),
|
||||
// array($sessionHandler, 'close'),
|
||||
// array($sessionHandler, 'read'),
|
||||
// array($sessionHandler, 'write'),
|
||||
// array($sessionHandler, 'destroy'),
|
||||
// array($sessionHandler, 'gc')
|
||||
// );
|
||||
// the following prevents unexpected effects when using objects as save handlers
|
||||
// register_shutdown_function('session_write_close');
|
||||
|
||||
// session_start();
|
||||
// proceed to set and retrieve values by key from $_SESSION
|
||||
|
||||
/* turn of dompdf autoload because we use composer */
|
||||
define('DOMPDF_ENABLE_AUTOLOAD', false);
|
||||
|
||||
// require_once __SITE_PATH.'/vendor/dompdf/dompdf/dompdf_config.inc.php';
|
||||
|
||||
/*
|
||||
Run Controller
|
||||
*/
|
||||
|
||||
$registry->router->loader();
|
3
Aiko/Aiko/Framework/Init.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Framework/Init.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
235
Aiko/Aiko/Framework/Model.php
Normal file
235
Aiko/Aiko/Framework/Model.php
Normal file
@ -0,0 +1,235 @@
|
||||
<?php
|
||||
namespace Aiko;
|
||||
|
||||
use Aiko\Database\Connections;
|
||||
use PDO;
|
||||
use PHPExcel;
|
||||
use Exception;
|
||||
|
||||
class Model
|
||||
{
|
||||
use Logdb {
|
||||
insertLog as protected ;
|
||||
}
|
||||
protected $registry;
|
||||
protected $query;
|
||||
protected $param = array();
|
||||
private $stmt;
|
||||
private $db;
|
||||
protected $preparedStatements;
|
||||
public $enabledDebugMode = false;
|
||||
|
||||
public function __construct($registry)
|
||||
{
|
||||
$this->registry = $registry;
|
||||
/* if($this->registry->config->dbMainConType!=='local')
|
||||
{
|
||||
$this->registry->db = Connections::getInstance($this->registry->config->dbMainConType);
|
||||
}else {
|
||||
$this->registry->db = Connections::getInstance(
|
||||
$this->registry->config->dbMainConType,
|
||||
$this->registry->config->host,
|
||||
$this->registry->config->socket,
|
||||
$this->registry->config->user,
|
||||
$this->registry->config->password
|
||||
);
|
||||
} */
|
||||
|
||||
|
||||
}
|
||||
|
||||
public function ConnectToOracle()
|
||||
{
|
||||
try {
|
||||
$host = $this->registry->config->hostOracle;
|
||||
$db = $this->registry->config->dbOracle;
|
||||
$user = $this->registry->config->userOracle;
|
||||
$pass = $this->registry->config->passwordOracle;
|
||||
// die($user.$pass);
|
||||
$this->registry->dbOracle = new PDO("oci:dbname=//$host:1521/$db;", "$user", "$pass", array(
|
||||
PDO::ATTR_TIMEOUT => 10,
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
));
|
||||
$this->registry->dbOracle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
$this->registry->dbOracle->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
|
||||
|
||||
} catch (\PDOException $e) {
|
||||
die("Sorry, an error has occured. Please try your request \n");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public function connectToDBPMA()
|
||||
{
|
||||
$this->registry->dbpma = Connections::getInstancePMA();
|
||||
}
|
||||
|
||||
protected function beginTransaction()
|
||||
{
|
||||
$this->registry->db->beginTransaction();
|
||||
}
|
||||
protected function commit()
|
||||
{
|
||||
$this->registry->db->commit();
|
||||
}
|
||||
protected function rollBack()
|
||||
{
|
||||
$this->registry->db->rollBack();
|
||||
}
|
||||
|
||||
protected function sendResponse($moreInfo, $messages, $status)
|
||||
{
|
||||
return array(
|
||||
"moreInfo" => $moreInfo,
|
||||
"messages" => $messages,
|
||||
"status" => $status,
|
||||
);
|
||||
}
|
||||
|
||||
public function connectToCarTal()
|
||||
{
|
||||
return Connections::getInstanceCartal($this->registry->config->dbCarTalType);
|
||||
}
|
||||
|
||||
public function connectToScada()
|
||||
{
|
||||
return Connections::getInstanceSCADA($this->registry->config->dbScadaType);
|
||||
}
|
||||
|
||||
protected function checkValidNikByEmpId($empId,$nik){
|
||||
try{
|
||||
$stmt=$this->registry->db->prepare('select nik from employement where nik=:nik and emp_profile_id=:emp_id');
|
||||
$stmt->bindValue(':nik',$nik,PDO::PARAM_STR);
|
||||
$stmt->bindValue(':emp_id',$empId,PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
if($stmt->rowCount()>0){
|
||||
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}catch(\PDOException $e){
|
||||
return false;
|
||||
}catch(\ErrorException $e){
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private function serializeColumn($arr = [], $isBinding = false)
|
||||
{
|
||||
$serialize = '';
|
||||
for ($i = 0; $i < count($arr); $i++) {
|
||||
if ($isBinding) {
|
||||
$serialize .= ":$arr[$i],";
|
||||
} else {
|
||||
if (is_numeric($arr[$i])) {
|
||||
$serialize .= "$arr[$i],";
|
||||
} else {
|
||||
$serialize .= "'$arr[$i]',";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return substr($serialize, 0, -1);
|
||||
}
|
||||
|
||||
public function prepareQuery($query)
|
||||
{
|
||||
if (isset($this->preparedStatements[$query])) {
|
||||
$stmt = $this->preparedStatements[$query];
|
||||
} else {
|
||||
// Call PDO::prepare.
|
||||
$stmt = $this->registry->db->prepare($query);
|
||||
$this->preparedStatements[$query] = $stmt;
|
||||
}
|
||||
return $stmt;
|
||||
}
|
||||
|
||||
private function checkDebugMode($stmt)
|
||||
{
|
||||
if ($this->enabledDebugMode) {
|
||||
$stmt->debugDumpParams();
|
||||
die();
|
||||
}
|
||||
}
|
||||
|
||||
protected function error($e, $name="")
|
||||
{
|
||||
if(!empty($name)){
|
||||
$this->registry->log->customError($name, 'Message: '. $e->getMessage() . ' | Line: '. $e->getLine(). ' | File: '. $e->getFile()) . ' | User: ' . \Helper::getSessionVar('username');
|
||||
}else{
|
||||
$this->registry->log->error('Message: '. $e->getMessage() . ' | Line: '. $e->getLine(). ' | File: '. $e->getFile() . ' | User: ' . \Helper::getSessionVar('username'));
|
||||
}
|
||||
}
|
||||
|
||||
protected function getColumnIndex($col)
|
||||
{
|
||||
$idx = \PHPExcel_Cell::columnIndexFromString($col);
|
||||
return $idx - 1;
|
||||
}
|
||||
|
||||
protected function getWorkSheetData($fileName, $sheetIndex)
|
||||
{
|
||||
$objPHPExcel = new PHPExcel();
|
||||
$inputFileType = \PHPExcel_IOFactory::identify($fileName);
|
||||
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
|
||||
|
||||
$objPHPExcel = $objReader->load($fileName);
|
||||
$objWorkSheet = $objPHPExcel->setActiveSheetIndex($sheetIndex);
|
||||
|
||||
return $objWorkSheet;
|
||||
}
|
||||
|
||||
/**
|
||||
* $type allowed
|
||||
* - time untuk jam
|
||||
* - date untuk tanggal
|
||||
*/
|
||||
protected function getColumnValue($objWorkSheet, $columnIndex, $row, $type='')
|
||||
{
|
||||
$result = $objWorkSheet->getCellByColumnAndRow($this->getColumnIndex($columnIndex), $row)->getValue();
|
||||
if(!empty($type)){
|
||||
$format = 'YYYY-MM-DD';
|
||||
$defValue = "1970-01-01";
|
||||
if($type=='time'){
|
||||
$defValue = "00:00:00";
|
||||
$format = 'hh:mm:ss';
|
||||
}
|
||||
if(empty($result)){
|
||||
return $defValue;
|
||||
}
|
||||
return \PHPExcel_Style_NumberFormat::toFormattedString(trim($result), $format);
|
||||
}
|
||||
|
||||
return trim($result);
|
||||
}
|
||||
|
||||
protected function saveFileData($file, $path, $allowedMime = [])
|
||||
{
|
||||
$filename = $file->getClientOriginalName();
|
||||
$mimeType = $file->getClientMimeType();
|
||||
$mimeClientAlowed = array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel');
|
||||
if(count($allowedMime)>0){
|
||||
$mimeClientAlowed = $allowedMime;
|
||||
}
|
||||
if (!in_array($mimeType, $mimeClientAlowed)) {
|
||||
throw new Exception('error file type');
|
||||
}
|
||||
$targetPath = $this->registry->config->base_storage. $path;
|
||||
$targetFile = str_replace('//', '/', $targetPath);
|
||||
$newfilename = $targetFile . '_' . time() . '_' . $filename;
|
||||
// store data to storage
|
||||
$file->move($targetFile, $newfilename);
|
||||
|
||||
return array('filename' => $filename, 'newfilename' => $newfilename);
|
||||
}
|
||||
|
||||
protected function isEmpty($param)
|
||||
{
|
||||
if(is_null($param) || empty($param) || !$param){
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
3
Aiko/Aiko/Framework/Model.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Framework/Model.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
107
Aiko/Aiko/Framework/Template.php
Normal file
107
Aiko/Aiko/Framework/Template.php
Normal file
@ -0,0 +1,107 @@
|
||||
<?php
|
||||
// class ini berfungsi untuk menentukan view nya yang digunakan
|
||||
namespace Aiko\Template;
|
||||
Class Template {
|
||||
|
||||
private $registry; // variable ini berfungsi untuk menampung object registry
|
||||
|
||||
private $vars = array(); // variable ini berfungsi untuk menyimpan variable variable yang digunakan
|
||||
// oleh templatenya
|
||||
|
||||
|
||||
function __construct($registry) {
|
||||
$this->registry = $registry; // set registry object
|
||||
|
||||
}
|
||||
|
||||
|
||||
public function __set($index, $value) // magic method yang berfungsi untuk set variable untuk template saja
|
||||
{
|
||||
$this->vars[$index] = $value;
|
||||
}
|
||||
|
||||
// ini method yang berfungsi untuk menampilkan view
|
||||
function show($name,$listJS= array(),$listCSS= array()) {
|
||||
// variable path berfungsi menyimpan path file view
|
||||
$path = __SITE_PATH .'/src/modules/'.$this->registry->ContPath. '/views' . '/' . $name . '.php';
|
||||
$pathJS= __SITE_PATH .'/src/modules/'.$this->registry->ContPath. '/js' . '/' . $name . '.js';
|
||||
$srcjs= __SERVERADDR.'/src/modules'.$this->registry->ContPath. '/js' . '/' . $name . '.js';
|
||||
$pathCSS= __SITE_PATH .'/src/modules/'.$this->registry->ContPath. '/css' . '/' . $name . '.css';
|
||||
$srccss= __SERVERADDR.'/src/modules'.$this->registry->ContPath. '/css' . '/' . $name . '.css';
|
||||
if (file_exists($path) == false)
|
||||
{
|
||||
throw new \Exception('Template not found in '. $path);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// Load variables, jadikan index array sebagai variable pada php
|
||||
foreach ($this->vars as $key => $value)
|
||||
{
|
||||
//set variable php
|
||||
$$key = $value;
|
||||
}
|
||||
|
||||
if(sizeof($listCSS)>0)
|
||||
{
|
||||
foreach ($listCSS as $val) {
|
||||
echo "<link href=\"$val\" rel=\"stylesheet\" type=\"text/css\" />";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// include file
|
||||
if (file_exists($pathCSS) == true)
|
||||
{
|
||||
echo "<link href=\"$srccss\" rel=\"stylesheet\" type=\"text/css\" />";
|
||||
}
|
||||
include ($path); // load view
|
||||
if (file_exists($pathJS) == true)
|
||||
{
|
||||
echo "<script type='text/javascript' src='$srcjs'></script>";
|
||||
}
|
||||
if(sizeof($listJS)>0)
|
||||
{
|
||||
foreach ($listJS as $val) {
|
||||
echo "<script type='text/javascript' src='$val'></script>";
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* method ini digunakan untuk menampilkan data dalam PDF
|
||||
* require dompdf
|
||||
*/
|
||||
public function getContentFile($name)
|
||||
{
|
||||
$path = __SITE_PATH .'/src/modules/'.$this->registry->ContPath. '/pdf' . '/' . $name . '.php';
|
||||
|
||||
if (file_exists($path) == false)
|
||||
{
|
||||
throw new \Exception('Template not found in '. $path);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Load variables, jadikan index array sebagai variable pada php
|
||||
foreach ($this->vars as $key => $value)
|
||||
{
|
||||
//set variable php
|
||||
$$key = $value;
|
||||
}
|
||||
|
||||
$obstart=ob_start();
|
||||
if ($obstart == false)
|
||||
{
|
||||
throw new \Exception('output bueffering not start ');
|
||||
return false;
|
||||
}
|
||||
|
||||
include ($path); // load view
|
||||
$out = ob_get_clean();
|
||||
return $out;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
?>
|
3
Aiko/Aiko/Framework/Template.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Framework/Template.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
353
Aiko/Aiko/Framework/Token.php
Normal file
353
Aiko/Aiko/Framework/Token.php
Normal file
@ -0,0 +1,353 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
use Aiko\Log;
|
||||
use Firebase\JWT\JWT;
|
||||
|
||||
class Token
|
||||
{
|
||||
|
||||
public function get_token($area = 'default')
|
||||
{
|
||||
$token = hash('sha512', mt_rand(0, mt_getrandmax()) . microtime(true));
|
||||
$_SESSION['token'] = $token;
|
||||
|
||||
return $token;
|
||||
}
|
||||
public function check_token($token, $area = 'default')
|
||||
{
|
||||
// var_dump($_SESSION);
|
||||
$sessiontoken = $this->get_token_from_session('token');
|
||||
// var_dump($sessiontoken);
|
||||
// exit();
|
||||
|
||||
|
||||
|
||||
|
||||
$valid = strlen($sessiontoken) == 128 && strlen($token) == 128 && $sessiontoken == $token;
|
||||
|
||||
$this->get_token($area); // refresh token
|
||||
|
||||
return $valid;
|
||||
}
|
||||
public function get_token_from_url()
|
||||
{
|
||||
$token = isset($_GET['token']) ? $_GET['token'] : '';
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
public function get_token_from_session($key)
|
||||
{
|
||||
$token = isset($_SESSION[$key]) ? $_SESSION[$key] : '';
|
||||
|
||||
return $token;
|
||||
}
|
||||
public function getTokenAuthUser()
|
||||
{
|
||||
$token = hash('sha512', mt_rand(0, mt_getrandmax()) . microtime(true));
|
||||
$_SESSION['tokenAuth'] = $token;
|
||||
|
||||
return $token;
|
||||
}
|
||||
public function check_tokenAuthUser($token)
|
||||
{
|
||||
$sessiontoken = $this->get_token_from_session('tokenAuth');
|
||||
$valid = strlen($sessiontoken) == 128 && strlen($token) == 128 && $sessiontoken == $token;
|
||||
if ($valid) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function set_cookie()
|
||||
{
|
||||
$result = password_hash('4pl1k4s1D1sd1K', PASSWORD_DEFAULT, array('cost' => 10));
|
||||
// $res = setcookie('XSRF-TOKEN', $result, time() + 86400, $_SERVER['REQUEST_URI'],'',false,false);
|
||||
|
||||
$res = setcookie('XSRF-TOKEN', $result, time() + 86400, '/');
|
||||
if ($res) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public function cek_cookie($clientCookie)
|
||||
{
|
||||
$result = false;
|
||||
if (isset($_COOKIE['XSRF-TOKEN'])) {
|
||||
$serverCookie = $_COOKIE['XSRF-TOKEN'];
|
||||
$result = $this->cek_hash($clientCookie, $serverCookie);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function cek_hash($clientCookie, $serverCookie)
|
||||
{
|
||||
if ($clientCookie == $serverCookie) {
|
||||
return $this->set_cookie();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static function wrapToken($jwt, $chipper)
|
||||
{
|
||||
try {
|
||||
if (strlen($chipper) <> 6) {
|
||||
throw new \ErrorException('chipper failed');
|
||||
}
|
||||
$headerPreffix = (int) substr($chipper, 0, 1);
|
||||
$headerSuffix = (int) substr($chipper, 1, 1);
|
||||
$payloadPreffix = (int) substr($chipper, 2, 1);
|
||||
$payloadSuffix = (int) substr($chipper, 3, 1);
|
||||
$signPreffix = (int) substr($chipper, 4, 1);
|
||||
$signSuffix = (int) substr($chipper, 5, 1);
|
||||
|
||||
$jwtPart = explode('.', $jwt);
|
||||
|
||||
$newJwt = self::randomChars($headerPreffix) . $jwtPart[0] . self::randomChars($headerSuffix);
|
||||
|
||||
$newJwt .= '.' . self::randomChars($payloadPreffix) . $jwtPart[1] . self::randomChars($payloadSuffix);
|
||||
|
||||
$newJwt .= '.' . self::randomChars($signPreffix) . $jwtPart[2] . self::randomChars($signSuffix);
|
||||
|
||||
return $newJwt;
|
||||
} catch (\Exception $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static function unWrapToken($jwt, $chipper)
|
||||
{
|
||||
try {
|
||||
if (strlen($chipper) <> 6) {
|
||||
throw new \ErrorException('chipper failed');
|
||||
}
|
||||
|
||||
$headerPreffix = (int) substr($chipper, 0, 1);
|
||||
$headerSuffix = (int) substr($chipper, 1, 1);
|
||||
$payloadPreffix = (int) substr($chipper, 2, 1);
|
||||
$payloadSuffix = (int) substr($chipper, 3, 1);
|
||||
$signPreffix = (int) substr($chipper, 4, 1);
|
||||
$signSuffix = (int) substr($chipper, 5, 1);
|
||||
|
||||
$jwtPart = explode('.', $jwt);
|
||||
|
||||
|
||||
$newString = self::removePreSuf($jwtPart[0], $headerPreffix, $headerSuffix);
|
||||
if ($newString == false) {
|
||||
throw new \ErrorException('failed clean wrapper header');
|
||||
}
|
||||
$header = $newString;
|
||||
|
||||
$newString = self::removePreSuf($jwtPart[1], $payloadPreffix, $payloadSuffix);
|
||||
if ($newString == false) {
|
||||
throw new \ErrorException('failed clean wrapper payload');
|
||||
}
|
||||
$payload = $newString;
|
||||
|
||||
$newString = self::removePreSuf($jwtPart[2], $signPreffix, $signSuffix);
|
||||
if ($newString == false) {
|
||||
throw new \ErrorException('failed clean wrapper sign');
|
||||
}
|
||||
$sign = $newString;
|
||||
|
||||
return $header . '.' . $payload . '.' . $sign;
|
||||
} catch (\ErrorException $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static function removePreSuf($string, $preffix, $suffix)
|
||||
{
|
||||
$jum = strlen(trim($string));
|
||||
$totWrapper = ($preffix + $suffix);
|
||||
$tot = $totWrapper + 10; // set minimum text
|
||||
if ($jum > $tot) {
|
||||
$total = $jum - $totWrapper;
|
||||
$newString = substr($string, $preffix, $total);
|
||||
return $newString;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function randomChars($numChars)
|
||||
{
|
||||
$str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuzwxyz';
|
||||
return substr(str_shuffle($str), 0, $numChars);
|
||||
}
|
||||
|
||||
public static function encodeJWT($serverName, $dataUser, $chipper = '000000')
|
||||
{
|
||||
|
||||
try {
|
||||
|
||||
$log = new Log('1');
|
||||
// $publicKey = file_get_contents('/Users/suhendra/mykey/suhendra_rsa.pub');
|
||||
|
||||
$privateKey = file_get_contents(__SITE_PATH . '/mykey/hcportalprivate.pem');
|
||||
|
||||
// $privateKey = openssl_get_privatekey('file:///Users/suhendra/mykey/suhendra_rsa','suh3ndr4');
|
||||
// var_dump($privateKey);
|
||||
|
||||
//$tokenId = base64_encode(\mcrypt_create_iv(32));
|
||||
$tokenId = base64_encode(\openssl_random_pseudo_bytes(64));
|
||||
// $random = mt_rand(0, 999999);
|
||||
// $random_string = sha1($random);
|
||||
//$tokenId = base64_encode(date('Y-m-d H:i:s'));
|
||||
$issuedAt = time();
|
||||
$notBefore = time();
|
||||
$expire = $notBefore + __EXPIREDJWT; // Adding 10 menit
|
||||
$expireReused = $notBefore + __LIFETIMEJWT; // Adding 2hari
|
||||
|
||||
/*
|
||||
* Create the token as an array
|
||||
*/
|
||||
$data = [
|
||||
'iat' => $issuedAt, // Issued at: time when the token was generated
|
||||
'jti' => $tokenId, // Json Token Id: an unique identifier for the token / A unique string, could be used to validate a token, but goes against not having a centralized issuer authority.
|
||||
'iss' => $serverName, // A string containing the name or identifier of the issuer application. Can be a domain name and can be used to discard tokens from other applications.
|
||||
'nbf' => $notBefore, // Timestamp of when the token should start being considered valid. Should be equal to or greater than iat. In this case, the token will begin to be valid 10 seconds
|
||||
'exp' => $expire, // Timestamp of when the token should cease to be valid. Should be greater than iat and nbf. In this case, the token will expire 60 seconds after being issued.
|
||||
'data' => $dataUser,
|
||||
];
|
||||
|
||||
$jwt = JWT::encode(
|
||||
$data, //Data to be encoded in the JWT
|
||||
$privateKey, // The signing key
|
||||
'RS256' // Algorithm used to sign the token, see https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40#section-3
|
||||
);
|
||||
|
||||
// var_dump($jwt);
|
||||
|
||||
$newJwt = self::wrapToken($jwt, $chipper);
|
||||
// var_dump($newJwt);
|
||||
|
||||
if ($newJwt == false) {
|
||||
throw new \ErrorException('Failed wrap Token');
|
||||
}
|
||||
|
||||
$dataUser['expired'] = $expire;
|
||||
$dataHeader = array(
|
||||
'jwt' => $newJwt,
|
||||
'tokenID' => $tokenId,
|
||||
'appID' => $serverName,
|
||||
'data' => $dataUser,
|
||||
'expired' => $expireReused
|
||||
);
|
||||
|
||||
return $dataHeader;
|
||||
} catch (\ErrorException $e) {
|
||||
$log->error('encode token token/decodeJWT' . $e->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static function decodeJWT($jwt, $chipper = '000000')
|
||||
{
|
||||
try {
|
||||
$log = new Log('1');
|
||||
|
||||
$publicKey = file_get_contents(__SITE_PATH . '/mykey/hcportalpublic.pem');
|
||||
|
||||
$newJwt = self::unWrapToken($jwt, $chipper);
|
||||
|
||||
$token = JWT::decode($newJwt, $publicKey, array('RS256'));
|
||||
|
||||
return $token;
|
||||
} catch (\DomainException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\UnexpectedValueException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\DateTime $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\SignatureInvalidException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\BeforeValidException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\Firebase\JWT\ExpiredException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static function decodeJWTNew($jwt, $chipper = '000000')
|
||||
{
|
||||
try {
|
||||
$log = new Log('1');
|
||||
|
||||
$publicKey = file_get_contents(__SITE_PATH . '/mykey/hcportalpublic.pem');
|
||||
|
||||
$newJwt = self::unWrapToken($jwt, $chipper);
|
||||
|
||||
$token = JWT::decode($newJwt, $publicKey, array('RS256'));
|
||||
return $token;
|
||||
} catch (\DomainException $e) {
|
||||
$log->error('decode token token/decodeJWT 2 ' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return 2;
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
$log->error('decode token token/decodeJWT 3' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return 3;
|
||||
} catch (\UnexpectedValueException $e) {
|
||||
$log->error('decode token token/decodeJWT 4' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
if ($e->getMessage() == 'Expired token') {
|
||||
return 8;
|
||||
}
|
||||
return 4;
|
||||
} catch (\DateTime $e) {
|
||||
$log->error('decode token token/decodeJWT 5' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return 5;
|
||||
} catch (\SignatureInvalidException $e) {
|
||||
$log->error('decode token token/decodeJWT 6' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return 6;
|
||||
} catch (\BeforeValidException $e) {
|
||||
$log->error('decode token token/decodeJWT 7' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return 7;
|
||||
} catch (\Firebase\JWT\ExpiredException $e) {
|
||||
$log->error('decode token token/decodeJWT 8' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return 8;
|
||||
}
|
||||
}
|
||||
|
||||
public static function decodePlainJWT($jwt, $key = null)
|
||||
{
|
||||
try {
|
||||
$log = new Log('1');
|
||||
|
||||
$token = JWT::decode($jwt, $key, array('HS256'));
|
||||
|
||||
return $token;
|
||||
} catch (\DomainException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\UnexpectedValueException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\Firebase\JWT\SignatureInvalidException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\Firebase\JWT\BeforeValidException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\Firebase\JWT\ExpiredException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
3
Aiko/Aiko/Framework/Token.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Framework/Token.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
33
Aiko/Aiko/Includes/App.config.php
Normal file
33
Aiko/Aiko/Includes/App.config.php
Normal file
@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
define('__NAMA_KOTA', '');
|
||||
|
||||
define('__CODE', '123456');
|
||||
|
||||
define('__KURS_DOLLAR', 140000);
|
||||
|
||||
define('__DAYINSECOND', 86400);
|
||||
|
||||
// define('__LIFETIMEJWT', 99999); // lifetime jwt 10 menit
|
||||
define('__EXPIREDJWT', 600); // lifetime jwt 10 menit
|
||||
|
||||
define('__LIFETIMEJWT', 600); // lifetime jwt 10 menit
|
||||
|
||||
|
||||
define('__END_GET_RANGE', 32400); //default end range , shift pulang current date + 9 jam
|
||||
|
||||
define('__START_GET_RANGE', 10800);
|
||||
|
||||
define('__START_GET_RANGE_NEXT', 10801); // end untuk hari besok nya
|
||||
|
||||
define('__END_MAX_RANGE', 32400); // jika besok libur maka jam di mabil sampai 9 jam berikut mnya
|
||||
|
||||
define('__SHORT_SHIFT', 18000); // short Shift
|
||||
|
||||
define('__ADDTIMEEXPIRED', 1296000);
|
||||
|
||||
define('_LEAVE_DOCUMENT', '/data/hcportal_docs/leavedocument');
|
||||
|
||||
define('_MAX_WORKING_HOUR',43200);
|
||||
|
||||
|
3
Aiko/Aiko/Includes/App.config.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Includes/App.config.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
169
Aiko/Aiko/Includes/config.php
Normal file
169
Aiko/Aiko/Includes/config.php
Normal file
@ -0,0 +1,169 @@
|
||||
<?php
|
||||
//file ini khusus digunakan untuk configurasi variable termasuk restrict access
|
||||
//[config]
|
||||
|
||||
//set time zone
|
||||
$config['time_zone'] = "Asia/Jakarta";
|
||||
|
||||
//set server address
|
||||
//server_address="https://hcportal.nabatisnack.co.id/src/api"
|
||||
$config['server_api_opx'] = "https://app.nabatisnack.co.id/nabati-group/opx/api";
|
||||
// $config['server_api_sap'] = "http://10.1.212.35:1080/sap/bc/zwspost?sap-client=300";
|
||||
$config['server_api_sap'] = "http://sapeccprdappaws.nabatisnack.co.id:1080/sap/bc/zwspost?sap-client=300";
|
||||
$config['server_address'] = "http://hcportal.local:3000/hcportal/src/api/";
|
||||
$config['storage_name'] = 'hcportal_docs';
|
||||
$config['base_storage'] = __SITE_PATH.'/'.$config['storage_name'];
|
||||
$config['base_link_access_doc'] = __SITE_PATH.'/'.$config['storage_name'];
|
||||
$config['base_storage'] = __SITE_PATH.'/'.$config['storage_name'];
|
||||
$config['base_link_access_doc'] = __SITE_PATH.'/'.$config['storage_name'];
|
||||
|
||||
//set restrict mode
|
||||
//default yes , jika yes maka yang bisa akses aplikasi hanya local saja,
|
||||
//dan jika computer lain di izinkan mengakses musti ip nya harus di daftarkan di variable ipconfig
|
||||
// jika tidak maka applikasi tidak bisa diakses
|
||||
// hati - hati jika menggunakan nginx sebagai interface ke client, karna nginx dan apache koneksi menggunakan
|
||||
// localhost. disini nginx sebagai proxy
|
||||
$config['restrict'] = "no";
|
||||
|
||||
// jika restrict yes maka daftarkan ip address yang boleh menggunakan aplikasi ini dibawah
|
||||
//ini
|
||||
//ipconfig[]='200.200.40.125'
|
||||
//ipconfig[]='192.168.1.30'
|
||||
|
||||
// available type main-testing-online, main-testing-local-network, main-production-local-network, main-production-online,main-production-localhost
|
||||
$config['dbMainConType'] ='main-production-aws';
|
||||
|
||||
// $config['dbScadaType'] = 'scada';
|
||||
// khusus untuk koneksi ke localhost
|
||||
$config['host'] = '10.1.200.30';
|
||||
$config['socket'] = '';
|
||||
$config['user'] = 'hcportal';
|
||||
$config['password'] = 'Hcp0rt4l!123&';
|
||||
|
||||
// $config['host'] = "10.1.200.218";
|
||||
// $config['socket'] = "/var/lib/mysql/mysql.sock";
|
||||
// $config['password'] = "Hcp0rt4l123";
|
||||
// $config['user'] = "hcportal";
|
||||
|
||||
$config['ajax'] = "on";
|
||||
|
||||
// setup app key untuk jwt
|
||||
|
||||
$config['app_key'] = "lsAen7EWbSKc/BlG+peItsDnO1okyQnrQsXV22DoVN0gUj7G/CC2QlAuZj8Z9aa6iPO7xjZhMplqjAb98WJ1Wg==";
|
||||
|
||||
// setup algoritma untuk jwt
|
||||
$config['algorithm'] = "HS512";
|
||||
|
||||
// setup servername untuk jwt
|
||||
$config['serverName'] = "hcportal.nabatisnack.co.id";
|
||||
|
||||
//environment setup
|
||||
// set developer / production. pada saat developer firephp aktif
|
||||
// cara penggunaan nya :
|
||||
// $this->registry->ab->info($content,$label);
|
||||
// $this->registry->ab->log($content,$label);
|
||||
// $this->registry->ab->warning($content,$label);
|
||||
// $this->registry->ab->error($content,$label);
|
||||
// $this->registry->ab->dump($content,$label);
|
||||
// $this->registry->ab->table($content,$label);
|
||||
// $this->registry->ab->trace($label);
|
||||
|
||||
|
||||
// jika pada saat production atau siap di upload ke server, pastikan
|
||||
// firephp di hapus pada composer.json dan set environment ke production
|
||||
$config['environment'] = "prod";
|
||||
$config['env'] = "developer";
|
||||
|
||||
// aktif log aplikasi dengan mengisi log 1 atau 0 untuk tidak aktif
|
||||
$config['log'] = "1";
|
||||
|
||||
// berikan nilai off jika output buffering off di php ini dan berikan on jika output buffering on di php.ini
|
||||
$config['ouput_buffering'] = "off";
|
||||
|
||||
|
||||
//cara penggunaan firePHP
|
||||
//1. pastikan dulu firebug nya sudah ada firephp
|
||||
//dibawah beberapa contoh penggunaan firePHP
|
||||
//$this->registry->fp->log($this->registry,'var_name');
|
||||
//$this->registry->fp->info('test info','Info Message');
|
||||
//$this->registry->fp->warn('test warn','Warn Message');
|
||||
//$this->registry->fp->error('test error','Error Message');
|
||||
//ini untuk fb (procedure API for firePHP)
|
||||
//contoh
|
||||
//fb::info($this->registry)
|
||||
|
||||
//set json path true or false, tru jika pada php versi belum support json, tetapi jika sudah support
|
||||
//jsonpath tidak perlu diaktifkan
|
||||
$config['jsonpath'] = false;
|
||||
// $json = '{ ... }';
|
||||
// $o = json_decode($json);
|
||||
// $match1 = jsonPath($o, "$..author");
|
||||
// $match2 = jsonPath($o, "$..author", array("resultType" => "PATH"));
|
||||
// $res1 = $parser->encode($match1);
|
||||
// $res2 = $parser->encode($match2);
|
||||
|
||||
// output
|
||||
// res1:
|
||||
// [ "Nigel Rees",
|
||||
// "Evelyn Waugh",
|
||||
// "Herman Melville",
|
||||
// "J. R. R. Tolkien"
|
||||
// ]
|
||||
//res2:
|
||||
//[ "$['store']['book'][0]['author']",
|
||||
// "$['store']['book'][1]['author']",
|
||||
// "$['store']['book'][2]['author']",
|
||||
// "$['store']['book'][3]['author']"
|
||||
|
||||
// daftarkan semua class - class name yang tidak perlu di load dengan menggunakan auto load
|
||||
// contoh class - class yang di load untuk plugin
|
||||
$config['listclassnotautoload'] = array("PEAR_Error");
|
||||
|
||||
|
||||
$config['smtp']="sandbox.smtp.mailtrap.io";
|
||||
$config['smtp_debug']=0;
|
||||
$config['smtp_debugtest']=false;
|
||||
$config['smtp_auth']=true;
|
||||
$config['port']=2525;
|
||||
$config['ssl']='';
|
||||
$config['mail_user']="efd747ae36a444";
|
||||
$config['mail_password']="b776c08d8e574c";
|
||||
|
||||
$config['edot_api_url'] = 'https://api-accounts.edot.id/';
|
||||
$config['edot_client_key'] = '8d0295087403c7414b4e0ce3baaf7ff1';
|
||||
$config['edot_client_secret'] = '99d6b4ea719fc1b7d7eac0b0';
|
||||
$config['edot_client_app_name'] = 'HCProduction';
|
||||
|
||||
|
||||
// $config['smtp'] = "mail.nabatisnack.co.id";
|
||||
// $config['smtp_debug'] = 0;
|
||||
// $config['smtp_debugtest'] = 1;
|
||||
// $config['smtp_auth'] = true;
|
||||
// $config['port'] = 587;
|
||||
// $config['ssl'] = [
|
||||
// 'verify_peer' => false,
|
||||
// 'verify_peer_name' => false,
|
||||
// 'allow_self_signed' => true
|
||||
// ];
|
||||
// $config['mail_user'] = "no-reply@nabatisnack.co.id";
|
||||
// $config['mail_password'] = "Nabati2017";
|
||||
|
||||
$config['whatsapp_endpoint']= "https://service-chat.qontak.com/api/open/v1/broadcasts/whatsapp/direct/";
|
||||
$config['wa_auth_url']= "https://service-chat.qontak.com/oauth/token";
|
||||
$config['channel_integration_id']="40f9ae05-a481-4b42-912d-feda75615903";
|
||||
$config['wa_username']="james_sinaga@pinusmerahabadi.co.id";
|
||||
$config['wa_password']="PMAoffice99_123";
|
||||
$config['wa_grant_type']="password";
|
||||
$config['wa_client_id']="RRrn6uIxalR_QaHFlcKOqbjHMG63elEdPTair9B9YdY";
|
||||
$config['wa_client_secret']="Sa8IGIh_HpVK1ZLAF0iFf7jU760osaUNV659pBIZR00";
|
||||
$config['wa_token_need_reload']=true; // ini di set true jika sudah 1 tahun ke depan saja
|
||||
$config['wa_token_name']='qontak_token';
|
||||
$config['whatsapp_sender']= "082123947499";
|
||||
$config['whatsapp_api_token']="kV838ObYkux0kDvIUlLzG6Q33r4FBThg7EiL80kUD8Ta7Ub1LKyBFGezljpdDK6X";
|
||||
$config['whatsapp_device_id']="6GZ69D";
|
||||
|
||||
$config['fcm_token'] = 'AAAApZfuw4I:APA91bE1CA3Mba_5mo0DQlfpRh50HrKygjWuPseHnXR517fP4ZITsWefMXkADbINNXhux494HoARcFe2gLybx0TEJvS6Igist7lerDW-JcRHuCBkCLAAYvfgwBwRFiPk3hRZTWrXpe8r';
|
||||
$config['api_geo_tz_endpoint'] = 'http://10.5.1.8:49160';
|
||||
$config['api_geo_tz_key'] = '34ca56dc6f424022a92e036357233310';
|
||||
// $config['api_geo_tz_endpoint'] = 'https://api.ipgeolocation.io';
|
||||
// $config['api_geo_tz_key'] = '34ca56dc6f424022a92e036357233310';
|
3
Aiko/Aiko/Includes/config.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Includes/config.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
99
Aiko/Aiko/Includes/db.config.php
Normal file
99
Aiko/Aiko/Includes/db.config.php
Normal file
@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
function getConfig($typeParam)
|
||||
{
|
||||
$config = array();
|
||||
$aTypeParam = explode('.', $typeParam);
|
||||
$type = $aTypeParam[0];
|
||||
$dbName = 'hcportal';
|
||||
if (count($aTypeParam) > 1) {
|
||||
$dbName = $aTypeParam[1];
|
||||
}
|
||||
switch ($type) {
|
||||
case 'main-testing-online':
|
||||
$config['dbms'] = "mysql";
|
||||
$config['host'] = "hcportal.nabatisnack.co.id:4867";
|
||||
$config['db'] = $dbName;
|
||||
$config['socket'] = "/var/lib/mysql/mysql.sock";
|
||||
$config['password'] = "Hcp0rt4l!";
|
||||
$config['user'] = "hcportal";
|
||||
break;
|
||||
|
||||
case 'main-testing-local-network':
|
||||
$config['dbms'] = "mysql";
|
||||
$config['host'] = "10.1.200.218:3899";
|
||||
$config['db'] = $dbName;
|
||||
$config['socket'] = "/var/lib/mysql/mysql.sock";
|
||||
$config['password'] = "Hcp0rt4l123";
|
||||
$config['user'] = "hcportal";
|
||||
break;
|
||||
|
||||
case 'main-production-local-network':
|
||||
$config['dbms'] = "mysql";
|
||||
$config['host'] = "10.1.200.218:3999";
|
||||
$config['db'] = "hcportal";
|
||||
$config['socket'] = "/var/lib/mysql/mysql.sock";
|
||||
$config['password'] = "Hcp0rt4l123prodapps";
|
||||
$config['user'] = "hcportal";
|
||||
break;
|
||||
case 'main-production-online':
|
||||
$config['dbms'] = "mysql";
|
||||
$config['host'] = "hcportal.nabatisnack.co.id:4855";
|
||||
$config['db'] = "hcportal";
|
||||
$config['socket'] = "/var/lib/mysql/mysql.sock";
|
||||
$config['password'] = "2@22hcn4b4t!GOremote";
|
||||
$config['user'] = "hcportal";
|
||||
break;
|
||||
case 'main-production-aws':
|
||||
$config['dbms'] = "mysql";
|
||||
$config['host'] = "10.5.1.8";
|
||||
$config['db'] = "hcportal";
|
||||
$config['socket'] = "/var/run/mysqld/mysqld.sock";
|
||||
$config['password'] = "NBT@23pch+11";
|
||||
$config['user'] = "hcportal";
|
||||
break;
|
||||
case 'cartal-dev-local':
|
||||
$config['dbms'] = "mysql";
|
||||
$config['host'] = "10.1.200.30:4867";
|
||||
$config['db'] = 'career_talentpool';
|
||||
$config['socket'] = "/var/lib/mysql/mysql.sock";
|
||||
$config['password'] = "Hcp0rt4l!";
|
||||
$config['user'] = "hcportal";
|
||||
break;
|
||||
case 'main-testing-local58':
|
||||
$config['dbms'] = "mysql";
|
||||
$config['host'] = "10.1.200.218:3888";
|
||||
$config['db'] = 'hcportal';
|
||||
$config['socket'] = "/var/lib/mysql/mysql.sock";
|
||||
$config['password'] = "Hcp0rt4l123";
|
||||
$config['user'] = "hcportal";
|
||||
break;
|
||||
case 'scada':
|
||||
$config['dbms'] = "pgsql";
|
||||
$config['host'] = "127.0.0.1";
|
||||
$config['port'] = "5432";
|
||||
$config['db'] = 'postgres';
|
||||
$config['password'] = "suh3ndr4";
|
||||
$config['user'] = "postgres";
|
||||
break;
|
||||
case 'testing-dev-local30':
|
||||
$config['dbms'] = "mysql";
|
||||
$config['host'] = "10.1.200.30:4867";
|
||||
$config['db'] = 'hcportal';
|
||||
$config['socket'] = "/var/lib/mysql/mysql.sock";
|
||||
$config['password'] = "Hcp0rt4l!";
|
||||
$config['user'] = "hcportal";
|
||||
break;
|
||||
default:
|
||||
// local
|
||||
$config['dbms'] = "";
|
||||
$config['host'] = "";
|
||||
$config['db'] = "";
|
||||
$config['socket'] = "";
|
||||
$config['password'] = "";
|
||||
$config['user'] = "";
|
||||
break;
|
||||
}
|
||||
|
||||
return $config;
|
||||
}
|
3
Aiko/Aiko/Includes/db.config.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Includes/db.config.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
2
Aiko/Aiko/Includes/db.config.php_encrypt
Normal file
2
Aiko/Aiko/Includes/db.config.php_encrypt
Normal file
File diff suppressed because one or more lines are too long
3
Aiko/Aiko/Includes/db.config.php_encrypt:Zone.Identifier
Normal file
3
Aiko/Aiko/Includes/db.config.php_encrypt:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
2
Aiko/Aiko/Includes/db.config__encryt.php_bck
Normal file
2
Aiko/Aiko/Includes/db.config__encryt.php_bck
Normal file
File diff suppressed because one or more lines are too long
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
10
Aiko/Aiko/Includes/index.html
Normal file
10
Aiko/Aiko/Includes/index.html
Normal file
@ -0,0 +1,10 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>403 Forbidden</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<p>Directory access is forbidden.</p>
|
||||
|
||||
</body>
|
||||
</html>
|
3
Aiko/Aiko/Includes/index.html:Zone.Identifier
Normal file
3
Aiko/Aiko/Includes/index.html:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
11
Aiko/Aiko/Includes/ipconfig.php
Normal file
11
Aiko/Aiko/Includes/ipconfig.php
Normal file
@ -0,0 +1,11 @@
|
||||
<?php
|
||||
/**
|
||||
* Daftarkan ip address yang bisa mengakses aplikasi selama dalam pengembangan atau user yang di bolehkan
|
||||
* @category Configurasi
|
||||
* @package Konfigurasi
|
||||
* @author hendra <hendra24pb@yahoo.com>
|
||||
* @license gpl /
|
||||
* @version 0.0
|
||||
* @link /
|
||||
*/
|
||||
$ipconfig = array('192.168.1.28','10.1.30.144');
|
3
Aiko/Aiko/Includes/ipconfig.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Includes/ipconfig.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
111
Aiko/Aiko/Includes/jsonpath.php
Normal file
111
Aiko/Aiko/Includes/jsonpath.php
Normal file
@ -0,0 +1,111 @@
|
||||
<?php
|
||||
/* JSONPath 0.8.1 - XPath for JSON
|
||||
*
|
||||
* Copyright (c) 2007 Stefan Goessner (goessner.net)
|
||||
* Licensed under the MIT (MIT-LICENSE.txt) licence.
|
||||
*/
|
||||
|
||||
// API function
|
||||
function jsonPath($obj, $expr, $args=null) {
|
||||
$jsonpath = new JsonPath();
|
||||
$jsonpath->resultType = ($args ? $args['resultType'] : "VALUE");
|
||||
$x = $jsonpath->normalize($expr);
|
||||
$jsonpath->obj = $obj;
|
||||
if ($expr && $obj && ($jsonpath->resultType == "VALUE" || $jsonpath->resultType == "PATH")) {
|
||||
$jsonpath->trace(preg_replace("/^\\$;/", "", $x), $obj, "$");
|
||||
if (count($jsonpath->result))
|
||||
return $jsonpath->result;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// JsonPath class (internal use only)
|
||||
class JsonPath {
|
||||
var $obj = null;
|
||||
var $resultType = "Value";
|
||||
var $result = array();
|
||||
var $subx = array();
|
||||
|
||||
// normalize path expression
|
||||
function normalize($x) {
|
||||
$x = preg_replace_callback("/[\['](\??\(.*?\))[\]']/", array(&$this, "_callback_01"), $x);
|
||||
$x = preg_replace(array("/'?\.'?|\['?/", "/;;;|;;/", "/;$|'?\]|'$/"),
|
||||
array(";", ";..;", ""),
|
||||
$x);
|
||||
$x = preg_replace_callback("/#([0-9]+)/", array(&$this, "_callback_02"), $x);
|
||||
$this->result = array(); // result array was temporarily used as a buffer ..
|
||||
return $x;
|
||||
}
|
||||
function _callback_01($m) { return "[#".(array_push($this->result, $m[1])-1)."]"; }
|
||||
function _callback_02($m) { return $this->result[$m[1]]; }
|
||||
|
||||
function asPath($path) {
|
||||
$x = explode(";", $path);
|
||||
$p = "$";
|
||||
for ($i=1,$n=count($x); $i<$n; $i++)
|
||||
$p .= preg_match("/^[0-9*]+$/", $x[$i]) ? ("[".$x[$i]."]") : ("['".$x[$i]."']");
|
||||
return $p;
|
||||
}
|
||||
function store($p, $v) {
|
||||
if ($p) array_push($this->result, ($this->resultType == "PATH" ? $this->asPath($p) : $v));
|
||||
return !!$p;
|
||||
}
|
||||
function trace($expr, $val, $path) {
|
||||
if ($expr) {
|
||||
$x = explode(";", $expr);
|
||||
$loc = array_shift($x);
|
||||
$x = implode(";", $x);
|
||||
|
||||
if (is_array($val) && array_key_exists($loc, $val))
|
||||
$this->trace($x, $val[$loc], $path.";".$loc);
|
||||
else if ($loc == "*")
|
||||
$this->walk($loc, $x, $val, $path, array(&$this, "_callback_03"));
|
||||
else if ($loc === "..") {
|
||||
$this->trace($x, $val, $path);
|
||||
$this->walk($loc, $x, $val, $path, array(&$this, "_callback_04"));
|
||||
}
|
||||
else if (preg_match("/,/", $loc)) // [name1,name2,...]
|
||||
for ($s=preg_split("/'?,'?/", $loc),$i=0,$n=count($s); $i<$n; $i++)
|
||||
$this->trace($s[$i].";".$x, $val, $path);
|
||||
else if (preg_match("/^\(.*?\)$/", $loc)) // [(expr)]
|
||||
$this->trace($this->evalx($loc, $val, substr($path,strrpos($path,";")+1)).";".$x, $val, $path);
|
||||
else if (preg_match("/^\?\(.*?\)$/", $loc)) // [?(expr)]
|
||||
$this->walk($loc, $x, $val, $path, array(&$this, "_callback_05"));
|
||||
else if (preg_match("/^(-?[0-9]*):(-?[0-9]*):?(-?[0-9]*)$/", $loc)) // [start:end:step] phyton slice syntax
|
||||
$this->slice($loc, $x, $val, $path);
|
||||
}
|
||||
else
|
||||
$this->store($path, $val);
|
||||
}
|
||||
function _callback_03($m,$l,$x,$v,$p) { $this->trace($m.";".$x,$v,$p); }
|
||||
function _callback_04($m,$l,$x,$v,$p) { if (is_array($v[$m])) $this->trace("..;".$x,$v[$m],$p.";".$m); }
|
||||
function _callback_05($m,$l,$x,$v,$p) { if ($this->evalx(preg_replace("/^\?\((.*?)\)$/","$1",$l),$v[$m])) $this->trace($m.";".$x,$v,$p); }
|
||||
|
||||
function walk($loc, $expr, $val, $path, $f) {
|
||||
foreach($val as $m => $v)
|
||||
call_user_func($f, $m, $loc, $expr, $val, $path);
|
||||
}
|
||||
function slice($loc, $expr, $v, $path) {
|
||||
$s = explode(":", preg_replace("/^(-?[0-9]*):(-?[0-9]*):?(-?[0-9]*)$/", "$1:$2:$3", $loc));
|
||||
$len=count($v);
|
||||
$start=(int)$s[0]?$s[0]:0;
|
||||
$end=(int)$s[1]?$s[1]:$len;
|
||||
$step=(int)$s[2]?$s[2]:1;
|
||||
$start = ($start < 0) ? max(0,$start+$len) : min($len,$start);
|
||||
$end = ($end < 0) ? max(0,$end+$len) : min($len,$end);
|
||||
for ($i=$start; $i<$end; $i+=$step)
|
||||
$this->trace($i.";".$expr, $v, $path);
|
||||
}
|
||||
function evalx($x, $v, $vname) {
|
||||
$name = "";
|
||||
$expr = preg_replace(array("/\\$/","/@/"), array("\$this->obj","\$v"), $x);
|
||||
$res = eval("\$name = $expr;");
|
||||
|
||||
if ($res === FALSE)
|
||||
print("(jsonPath) SyntaxError: " . $expr);
|
||||
else
|
||||
return $name;
|
||||
}
|
||||
}
|
||||
?>
|
3
Aiko/Aiko/Includes/jsonpath.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Includes/jsonpath.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
384
Aiko/Aiko/Libs/ApprovalRequest/ApprovalRequest.php
Normal file
384
Aiko/Aiko/Libs/ApprovalRequest/ApprovalRequest.php
Normal file
@ -0,0 +1,384 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* ApprovalRequest class is wrapper for approval trait.
|
||||
*
|
||||
* the benefit of using this class
|
||||
*
|
||||
* no need to pass the main table name frequently. it handled in construction process
|
||||
* every method safely handled by try catch.
|
||||
* every transaction method using db transaction
|
||||
*
|
||||
* if there is a case to handle multiple approval with different main table name, use as follow inside constructor
|
||||
*
|
||||
* private $approvalRequestA;
|
||||
* private $approvalRequestB;
|
||||
*
|
||||
* $this-approvalRequestA = new AppovalRequest($registry, $patternObj, 'my_main_approval_table_a', 'my_module_name');
|
||||
* $this-approvalRequestB = new AppovalRequest($registry, $patternObj, 'my_main_approval_table_b', 'my_module_name');
|
||||
*
|
||||
*/
|
||||
class ApprovalRequest
|
||||
{
|
||||
use ApprovalRequestTrait;
|
||||
|
||||
protected $registry;
|
||||
|
||||
protected $moduleName = 'ApprovalRequest';
|
||||
|
||||
protected $tableName;
|
||||
|
||||
/** @var \modules\approvalpattern\model\Approvalpattern $approvalPatternObj */
|
||||
protected $approvalPatternObj;
|
||||
|
||||
public function __construct($registry, $approvalPatternObj, $tableName, $moduleName = '')
|
||||
{
|
||||
$this->registry = $registry;
|
||||
$this->approvalPatternObj = $approvalPatternObj;
|
||||
$this->tableName = $tableName;
|
||||
$this->moduleName = $moduleName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Approval create
|
||||
*
|
||||
* Please handle try catch error in implementation,
|
||||
* because this always combined with other logic.
|
||||
*
|
||||
* @uses ApprovalPattern@setApproval
|
||||
*
|
||||
* @param mixed $transactionId
|
||||
* @param string $requestBy
|
||||
* @param string $action
|
||||
* @param string $startDate is from setApproval
|
||||
* @param string $endDate is from setApproval
|
||||
* @param string $effectiveDate is effective by for request by. leave it null if only need latest active employee until this day
|
||||
*
|
||||
*/
|
||||
public function create(
|
||||
$requestBy,
|
||||
$transactionId,
|
||||
$action,
|
||||
$startDate = '1970-01-01',
|
||||
$endDate = '1970-01-01',
|
||||
$effectiveDate = null
|
||||
) {
|
||||
return $this->createApprovalRequest(
|
||||
$this->approvalPatternObj,
|
||||
$this->tableName,
|
||||
$requestBy,
|
||||
$transactionId,
|
||||
$action,
|
||||
$startDate,
|
||||
$endDate,
|
||||
$effectiveDate
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method used for approve request.
|
||||
* it already handle transaction within try-catch
|
||||
*
|
||||
* @param mixed $transactionId is an id of main table
|
||||
* @param string $requestBy
|
||||
*
|
||||
*/
|
||||
public function approve(
|
||||
$requestBy,
|
||||
$transactionId,
|
||||
$startDateAs = '1970-01-01',
|
||||
$endDateAs = '1970-01-01'
|
||||
) {
|
||||
try {
|
||||
$this->registry->db->beginTransaction();
|
||||
$approve = $this->approveRequest($this->approvalPatternObj, $this->tableName, $requestBy, $transactionId, $startDateAs, $endDateAs);
|
||||
if ($approve == false) {
|
||||
throw new Exception("Failed approval");
|
||||
}
|
||||
if ($approve['isSuccess'] == 0) {
|
||||
$this->registry->db->rollBack();
|
||||
return $approve;
|
||||
}
|
||||
$this->registry->db->commit();
|
||||
return $approve;
|
||||
} catch (Exception $e) {
|
||||
$this->registry->db->rollback();
|
||||
$this->registry
|
||||
->log
|
||||
->error("$this->moduleName / action : approve"
|
||||
. $e->getMessage() . ', Line: '
|
||||
. $e->getLine() . ', User: '
|
||||
. \Helper::getSessionVar('username'));
|
||||
return array(
|
||||
'isSuccess' => 0,
|
||||
'isLastApproval' => -1,
|
||||
'approval_id' => $requestBy,
|
||||
'message' => 'Internal server error'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method used for reject request
|
||||
* it already handle transaction within try-catch
|
||||
*
|
||||
* @param mixed $transactionId is an id of main table
|
||||
* @param string $requestBy
|
||||
* @param string $comment is reject comment
|
||||
*
|
||||
*/
|
||||
public function reject(
|
||||
$requestBy,
|
||||
$transactionId,
|
||||
$comment = '-',
|
||||
$startDateAs = '1970-01-01',
|
||||
$endDateAs = '1970-01-01'
|
||||
) {
|
||||
try {
|
||||
$this->registry->db->beginTransaction();
|
||||
$reject = $this->rejectRequest($this->approvalPatternObj, $this->tableName, $requestBy, $transactionId, $comment, $startDateAs, $endDateAs);
|
||||
if ($reject == false) {
|
||||
throw new Exception("Error reject", 1);
|
||||
}
|
||||
if (!$reject['isSuccess']) {
|
||||
$this->registry->db->rollBack();
|
||||
return $reject;
|
||||
}
|
||||
$this->registry->db->commit();
|
||||
return $reject;
|
||||
} catch (Exception $e) {
|
||||
$this->registry->db->rollback();
|
||||
$this->registry
|
||||
->log
|
||||
->error("$this->moduleName / action : reject"
|
||||
. $e->getMessage() . ', Line: '
|
||||
. $e->getLine() . ', User: '
|
||||
. \Helper::getSessionVar('username'));
|
||||
return array(
|
||||
'isSuccess' => 0,
|
||||
'isLastApproval' => -1,
|
||||
'approval_id' => $transactionId,
|
||||
'message' => 'Internal server error'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method used for approve multiple request.
|
||||
*
|
||||
* @param string $requestBy
|
||||
* @param array<mixed> $transactionIds is array id of main table
|
||||
*
|
||||
* format of $transactionIds is [1, 2, 3]
|
||||
* use Helper::getArrayValueByKey($myArrayOrObject, 'id') to extract only id from multidimentional array object
|
||||
*
|
||||
*/
|
||||
public function batchApprove(
|
||||
$requestBy,
|
||||
$transactionIds = [],
|
||||
$startDateAs = '1970-01-01',
|
||||
$endDateAs = '1970-01-01'
|
||||
) {
|
||||
$success = [];
|
||||
$failed = [];
|
||||
$ctr = count($transactionIds);
|
||||
for ($i = 0; $i < $ctr; $i++) {
|
||||
$result = $this->approve($requestBy, $transactionIds[$i], $startDateAs, $endDateAs);
|
||||
if ($result['isSuccess'] == 1) {
|
||||
array_push($success, $result);
|
||||
} else {
|
||||
array_push($failed, $result);
|
||||
}
|
||||
}
|
||||
return ['success' => $success, 'failed' => $failed];
|
||||
}
|
||||
|
||||
/**
|
||||
* This method used for reject multiple request
|
||||
*
|
||||
* @param string $requestBy
|
||||
* @param array<mixed> $transactionIds is array id of main table
|
||||
* @param string $comment is reject comment
|
||||
*
|
||||
* format of $transactionIds is [1, 2, 3]
|
||||
* use Helper::getArrayValueByKey($myArrayOrObject, 'id') to extract only id from multidimentional array object
|
||||
*
|
||||
*/
|
||||
public function batchReject(
|
||||
$requestBy,
|
||||
$transactionIds = [],
|
||||
$comment = '',
|
||||
$startDateAs = '1970-01-01',
|
||||
$endDateAs = '1970-01-01'
|
||||
) {
|
||||
$success = [];
|
||||
$failed = [];
|
||||
$ctr = count($transactionIds);
|
||||
for ($i = 0; $i < $ctr; $i++) {
|
||||
$result = $this->reject($requestBy, $transactionIds[$i], $comment, $startDateAs, $endDateAs);
|
||||
if ($result['isSuccess'] == 1) {
|
||||
array_push($success, $result);
|
||||
} else {
|
||||
array_push($failed, $result);
|
||||
}
|
||||
}
|
||||
return ['success' => $success, 'failed' => $failed];
|
||||
}
|
||||
|
||||
/**
|
||||
* This method used for unapprove multiple request
|
||||
*
|
||||
* @param string $requestBy
|
||||
* @param array<mixed> $transactionIds is array id of main table
|
||||
*
|
||||
* format of $transactionIds is [1, 2, 3]
|
||||
* use Helper::getArrayValueByKey($myArrayOrObject, 'id') to extract only id from multidimentional array object
|
||||
*
|
||||
*/
|
||||
public function batchUnapprove(
|
||||
$requestBy,
|
||||
$transactionIds = []
|
||||
) {
|
||||
$success = [];
|
||||
$failed = [];
|
||||
$ctr = count($transactionIds);
|
||||
for ($i = 0; $i < $ctr; $i++) {
|
||||
$result = $this->unApprove($requestBy, $transactionIds[$i]);
|
||||
if ($result['isSuccess'] == 1) {
|
||||
array_push($success, $result);
|
||||
} else {
|
||||
array_push($failed, $result);
|
||||
}
|
||||
}
|
||||
return ['success' => $success, 'failed' => $failed];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This method used for unReject multiple request
|
||||
*
|
||||
* @param string $requestBy
|
||||
* @param array<mixed> $transactionIds is array id of main table
|
||||
*
|
||||
* format of $transactionIds is [1, 2, 3]
|
||||
* use Helper::getArrayValueByKey($myArrayOrObject, 'id') to extract only id from multidimentional array object
|
||||
*
|
||||
*/
|
||||
public function batchUnreject(
|
||||
$requestBy,
|
||||
$transactionIds = []
|
||||
) {
|
||||
return $this->batchUnapprove($requestBy, $transactionIds);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This method used for unapprove request
|
||||
* it already handle transaction within try-catch
|
||||
*
|
||||
* @param string $requestBy is usually the login user
|
||||
* @param mixed $transactionId is an id of main table
|
||||
*
|
||||
*/
|
||||
public function unApprove($requestBy, $transactionId)
|
||||
{
|
||||
try {
|
||||
$this->registry->db->beginTransaction();
|
||||
$approval = $this->unapproveRequest($this->approvalPatternObj, $this->tableName, $requestBy, $transactionId);
|
||||
if ($approval == false) {
|
||||
throw new Exception("Failed unapprove");
|
||||
}
|
||||
if ($approval['isSuccess'] == 0) {
|
||||
$this->registry->db->rollBack();
|
||||
return $approval;
|
||||
}
|
||||
$this->registry->db->commit();
|
||||
return $approval;
|
||||
} catch (Exception $e) {
|
||||
$this->registry->db->rollback();
|
||||
$this->registry
|
||||
->log
|
||||
->error("$this->moduleName / action : unApprove"
|
||||
. $e->getMessage() . ', Line: '
|
||||
. $e->getLine() . ', User: '
|
||||
. \Helper::getSessionVar('username'));
|
||||
return array(
|
||||
'isSuccess' => 0,
|
||||
'is_last_approval_approved' => -1,
|
||||
'message' => 'Internal server error'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method used for unreject request
|
||||
* it already handle transaction within try-catch
|
||||
*
|
||||
* @param string $requestBy is usually the login user
|
||||
* @param mixed $transactionId is an id of main table
|
||||
*
|
||||
*/
|
||||
public function unReject($requestBy, $transactionId)
|
||||
{
|
||||
try {
|
||||
$this->registry->db->beginTransaction();
|
||||
$approval = $this->unrejectRequest($this->approvalPatternObj, $this->tableName, $transactionId, $requestBy);
|
||||
if ($approval == false) {
|
||||
throw new Exception("Failed unApprove");
|
||||
}
|
||||
if ($approval['isSuccess'] == 0) {
|
||||
$this->registry->db->rollBack();
|
||||
return $approval;
|
||||
}
|
||||
$this->registry->db->commit();
|
||||
return $approval;
|
||||
} catch (Exception $e) {
|
||||
$this->registry->db->rollback();
|
||||
$this->registry
|
||||
->log
|
||||
->error("$this->moduleName / action : unReject"
|
||||
. $e->getMessage() . ', Line: '
|
||||
. $e->getLine() . ', User: '
|
||||
. \Helper::getSessionVar('username'));
|
||||
return array(
|
||||
'isSuccess' => 0,
|
||||
'is_last_approval_approved' => -1,
|
||||
'message' => 'Internal server error'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method used for fetch latest approval from db
|
||||
*
|
||||
* @param mixed $transactionId
|
||||
* @param bool $sigle
|
||||
*
|
||||
* if single true the return will be single array, if false will be multi dimensional array
|
||||
*
|
||||
*/
|
||||
public function latestApproval($transactionId, $single = false)
|
||||
{
|
||||
$data = $this->getLatestApproval($this->tableName, $transactionId);
|
||||
if ($single) {
|
||||
return count($data) > 0 ? $data[0] : [];
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This method used for fetch info styled approval
|
||||
*
|
||||
* @param mixed $transactionId
|
||||
*
|
||||
*/
|
||||
public function infoApproval($transactionId)
|
||||
{
|
||||
return $this->getApprovalList($this->tableName . "_approval", $this->tableName . "_id", $transactionId);
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
648
Aiko/Aiko/Libs/ApprovalRequest/ApprovalRequestTrait.php
Normal file
648
Aiko/Aiko/Libs/ApprovalRequest/ApprovalRequestTrait.php
Normal file
@ -0,0 +1,648 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
use ErrorException;
|
||||
use PDO;
|
||||
use PDOException;
|
||||
|
||||
/**
|
||||
* This trait is used to manage approval process easier
|
||||
* it follow approval pattern naming conventions.
|
||||
*
|
||||
* example:
|
||||
*
|
||||
* if the main table is ghk then the child approval table should derrives its name.
|
||||
*
|
||||
* ghk [main table]
|
||||
* ghk_approval [approval_table] with foreign ghk_id
|
||||
* ghk_approval_group [approval_group_table] with foreign ghk_approval_id
|
||||
*
|
||||
* every $mainTable supplied in method will be generated as below
|
||||
* {$mainTable}_approval [table],
|
||||
* {$mainTable}_approval_group [table],
|
||||
* {$mainTable}_id [column],
|
||||
* {$mainTable}_approval_id [column],
|
||||
* {$mainTable}_approval_group_id [column]
|
||||
*/
|
||||
trait ApprovalRequestTrait
|
||||
{
|
||||
private function getApprovalList($table, $whereColumn, $transactionId)
|
||||
{
|
||||
try {
|
||||
$sql = "SELECT a.id,
|
||||
getEmpName(a.approved_by) AS name,
|
||||
a.approval_type,
|
||||
a.approval_date,
|
||||
a.reject_comment,
|
||||
a.approval_status,
|
||||
d.emp_grade AS grade,
|
||||
c.photo_address AS images,
|
||||
e.description AS job_title
|
||||
FROM `$table` a
|
||||
INNER JOIN employement b ON a.approved_by = b.nik
|
||||
INNER JOIN emp_profiles c ON b.emp_profile_id = c.id
|
||||
LEFT JOIN emp_job d ON b.nik = d.nik AND d.effective_date = (SELECT ej.effective_date FROM emp_job ej WHERE ej.nik = d.nik ORDER BY ej.effective_date DESC LIMIT 1)
|
||||
LEFT JOIN mpp_detail e ON e.id = d.mpp_detail_id
|
||||
LEFT JOIN org_layer f ON e.org_layer_id = f.id
|
||||
WHERE a.$whereColumn =:id AND a.approval_status != '0'
|
||||
ORDER BY a.approval_level";
|
||||
$stmt = $this->registry->db->prepare($sql);
|
||||
$stmt->bindValue(':id', $transactionId, PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
$storage = new Storage($this->registry);
|
||||
$configs = [];
|
||||
for ($i = 0; $i < count($res); $i++) {
|
||||
$avatar = null;
|
||||
if ($res[$i]['images'] != null) {
|
||||
$avatar = $storage->url($res[$i]['images'], 'emp_document');
|
||||
}
|
||||
$appStatus = [
|
||||
'text' => 'Undefined',
|
||||
'color' => 'grey-700-fg'
|
||||
];
|
||||
|
||||
$icon = [
|
||||
'color_fg' => 'grey-500-fg',
|
||||
'color_bg' => 'grey-200-bg',
|
||||
'icon' => 'icon-account-alert'
|
||||
];
|
||||
switch ($res[$i]['approval_status']) {
|
||||
case '1':
|
||||
$appStatus['text'] = 'Waiting Approval';
|
||||
$appStatus['color'] = 'blue-800-fg';
|
||||
$icon['color_fg'] = 'blue-700-fg';
|
||||
$icon['color_bg'] = 'blue-50-bg';
|
||||
$icon['icon'] = 'icon-timelapse';
|
||||
break;
|
||||
case '2':
|
||||
$appStatus['text'] = 'Approved';
|
||||
$appStatus['color'] = 'green-800-fg';
|
||||
$icon['color_fg'] = 'green-700-fg';
|
||||
$icon['color_bg'] = 'green-50-bg';
|
||||
$icon['icon'] = 'icon-check-circle';
|
||||
break;
|
||||
case '4':
|
||||
$appStatus['text'] = 'Rejected';
|
||||
$appStatus['color'] = 'red-800-fg';
|
||||
$icon['color_fg'] = 'red-700-fg';
|
||||
$icon['color_bg'] = 'red-50-bg';
|
||||
$icon['icon'] = 'icon-close-circle-outline';
|
||||
break;
|
||||
}
|
||||
$config = [
|
||||
'icon' => $icon,
|
||||
'detail' => [
|
||||
'title' => $appStatus,
|
||||
'subtitle' => $res[$i]['approval_date'],
|
||||
'comment' => $res[$i]['reject_comment']
|
||||
],
|
||||
'card' => [
|
||||
'title' => 'Approve as ' . '(' . strtoupper($res[$i]['approval_type']) . ')',
|
||||
'image' => $avatar,
|
||||
'content' => [
|
||||
'main' => $res[$i]['name'],
|
||||
'sub' => $res[$i]['job_title'] . ' | ' . $res[$i]['grade']
|
||||
]
|
||||
],
|
||||
'meta' => $res[$i]
|
||||
];
|
||||
array_push($configs, $config);
|
||||
}
|
||||
return $configs;
|
||||
} catch (PDOException $e) {
|
||||
$log = new Log('0');
|
||||
$log->error('ApprovalHelper / getApprovalList :'
|
||||
. $e->getMessage() . ', Line: '
|
||||
. $e->getLine() . ', File: '
|
||||
. $e->getFile());
|
||||
return [];
|
||||
} catch (ErrorException $e) {
|
||||
$log = new Log('0');
|
||||
$log->error('ApprovalHelper / getApprovalList :'
|
||||
. $e->getMessage() . ', Line: '
|
||||
. $e->getLine() . ', File: '
|
||||
. $e->getFile());
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Approval createApprovalRequest
|
||||
*
|
||||
* dependencies already resolved by internal function with $mainTable as param
|
||||
*
|
||||
* @uses ApprovalPattern@setApproval
|
||||
*
|
||||
* @param mixed $approvalPatternObj
|
||||
* @param string $mainTable main table approval that will be concated with other table related to query
|
||||
* @param string $requestBy
|
||||
* @param mixed $transactionId
|
||||
* @param string $action
|
||||
* @param string $startDate is from setApproval
|
||||
* @param string $endDate is from setApproval
|
||||
* @param string $effectiveDate is effective by for request by. leave it null if only need latest active employee until this day
|
||||
*
|
||||
* handle try catch in implementation
|
||||
*/
|
||||
private function createApprovalRequest(
|
||||
$approvalPatternObj,
|
||||
$mainTable,
|
||||
$requestBy,
|
||||
$transactionId,
|
||||
$action,
|
||||
$startDate = '1970-01-01',
|
||||
$endDate = '1970-01-01',
|
||||
$effectiveDate = null
|
||||
) {
|
||||
$stmtApproval = $this->_stmtApprovalSetApproval($mainTable);
|
||||
$stmtGroupApproval = $this->_stmtGroupApproval($mainTable);
|
||||
$employee = $this->getEmployee($requestBy, $effectiveDate);
|
||||
if (count($employee) == 0) {
|
||||
throw new ErrorException("Employee not found");
|
||||
}
|
||||
/** @var \modules\approvalpattern\model\Approvalpattern $approvalPatternObj */
|
||||
return $approvalPatternObj->setApproval(
|
||||
$transactionId,
|
||||
$action,
|
||||
$employee['grade'],
|
||||
$employee['company_id'],
|
||||
$employee['country_id'],
|
||||
$employee['sub_area_id'],
|
||||
$requestBy,
|
||||
$startDate,
|
||||
$endDate,
|
||||
$requestBy,
|
||||
$stmtApproval,
|
||||
$stmtGroupApproval
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Approval approve request
|
||||
*
|
||||
* hard coded approval_status is 2. dependencies already resolved by internal function with $mainTable as param
|
||||
*
|
||||
* @uses getApproveDependencies
|
||||
* @uses ApprovalPattern@doApproval
|
||||
*
|
||||
* @param mixed $approvalPatternObj
|
||||
* @param string $mainTable main table approval that will be concated with other table related to query
|
||||
* @param string $requestBy
|
||||
* @param mixed $transactionId
|
||||
* @param string $startDateAs
|
||||
* @param string $endDateAS
|
||||
*
|
||||
*
|
||||
* handle try catch in implementation
|
||||
*/
|
||||
private function approveRequest(
|
||||
$approvalPatternObj,
|
||||
$mainTable,
|
||||
$requestBy,
|
||||
$transactionId,
|
||||
$startDateAs = '1970-01-01',
|
||||
$endDateAS = '1970-01-01'
|
||||
) {
|
||||
$deps = $this->getApproveDependencies($mainTable, $startDateAs, $endDateAS);
|
||||
/** @var \modules\approvalpattern\model\Approvalpattern $approvalPatternObj */
|
||||
return $approvalPatternObj->doApproval(
|
||||
$transactionId,
|
||||
$requestBy,
|
||||
'2',
|
||||
$deps[0],
|
||||
$deps[1],
|
||||
$deps[2],
|
||||
$deps[3]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Approval reject request
|
||||
*
|
||||
* hard coded approval_status is 4. dependencies already resolved by internal function with $mainTable as param
|
||||
*
|
||||
* @uses getRejectDependencies
|
||||
* @uses ApprovalPattern@doApproval
|
||||
*
|
||||
* @param mixed $approvalPatternObj
|
||||
* @param string $mainTable main table approval that will be concated with other table related to query
|
||||
* @param string $requestBy
|
||||
* @param mixed $transactionId
|
||||
* @param string $comment
|
||||
* @param string $startDateAs
|
||||
* @param string $endDateAS
|
||||
*
|
||||
* handle try catch in implementation
|
||||
*/
|
||||
private function rejectRequest(
|
||||
$approvalPatternObj,
|
||||
$mainTable,
|
||||
$requestBy,
|
||||
$transactionId,
|
||||
$comment,
|
||||
$startDateAs = '1970-01-01',
|
||||
$endDateAS = '1970-01-01'
|
||||
) {
|
||||
$deps = $this->getRejectDependencies($mainTable, $startDateAs, $endDateAS);
|
||||
/** @var \modules\approvalpattern\model\Approvalpattern $approvalPatternObj */
|
||||
return $approvalPatternObj->doApproval(
|
||||
$transactionId,
|
||||
$requestBy,
|
||||
'4',
|
||||
$deps[0],
|
||||
$deps[1],
|
||||
$deps[2],
|
||||
$deps[3],
|
||||
$comment
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Approval unapprove request
|
||||
*
|
||||
* dependencies already resolved by internal function with $mainTable as param
|
||||
*
|
||||
* @uses getRejectDependencies
|
||||
* @uses ApprovalPattern@doUnApprove
|
||||
*
|
||||
* @param mixed $approvalPatternObj
|
||||
* @param string $mainTable main table approval that will be concated with other table related to query
|
||||
* @param string $requestBy
|
||||
* @param mixed $transactionId
|
||||
*
|
||||
* handle try catch in implementation
|
||||
*/
|
||||
private function unapproveRequest($approvalPatternObj, $mainTable, $requestBy, $transactionId)
|
||||
{
|
||||
$deps = $this->getUnapproveDependencies($mainTable);
|
||||
/** @var \modules\approvalpattern\model\Approvalpattern $approvalPatternObj */
|
||||
return $approvalPatternObj->doUnApprove(
|
||||
$transactionId,
|
||||
$requestBy,
|
||||
$deps[0],
|
||||
$deps[1],
|
||||
$deps[2],
|
||||
$deps[3],
|
||||
$deps[4]
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Approval unreject request
|
||||
*
|
||||
* dependencies already resolved by internal function with $mainTable as param
|
||||
*
|
||||
* @uses getRejectDependencies
|
||||
* @uses ApprovalPattern@doUnApprove
|
||||
*
|
||||
* @param mixed $approvalPatternObj
|
||||
* @param string $mainTable main table approval that will be concated with other table related to query
|
||||
* @param string $requestBy
|
||||
* @param mixed $transactionId
|
||||
*
|
||||
* handle try catch in implementation
|
||||
*/
|
||||
private function unrejectRequest($approvalPatternObj, $mainTable, $requestBy, $transactionId)
|
||||
{
|
||||
$deps = $this->getUnrejectDependencies($mainTable);
|
||||
/** @var \modules\approvalpattern\model\Approvalpattern $approvalPatternObj */
|
||||
return $approvalPatternObj->doUnApprove(
|
||||
$transactionId,
|
||||
$requestBy,
|
||||
$deps[0],
|
||||
$deps[1],
|
||||
$deps[2],
|
||||
$deps[3],
|
||||
$deps[4]
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Query helper to resolve stmt dependencies for approval
|
||||
*
|
||||
* @param string $mainTable main table approval that will be concated with other table related to query
|
||||
* @param string $startDateAs
|
||||
* @param string $endDateAS
|
||||
*
|
||||
* @return array
|
||||
* return will be array in exact order, it adjusted with doApproval parameters from ApprovalPattern
|
||||
* [
|
||||
* $stmtApproval,
|
||||
* $stmtUpdateApproval,
|
||||
* $stmtUpdateNextApproval,
|
||||
* $stmtGetLevel
|
||||
* ]
|
||||
*
|
||||
* example :
|
||||
*
|
||||
* $mainTable = 'incentive_hold_request';
|
||||
*
|
||||
* this method will resolve query to following table and column
|
||||
* [table] incentive_hold_request_group_approval,
|
||||
* [table] incentive_hold_request_approval,
|
||||
* [table] incentive_hold_request,
|
||||
* [column] incentive_hold_request_approval_id,
|
||||
* [column] incentive_hold_request_id
|
||||
*
|
||||
* please using with cautions. this is just query builder to help make standard approval faster.
|
||||
* if the feature need more advance customization, please do as usual.
|
||||
*
|
||||
*/
|
||||
private function getApproveDependencies($mainTable, $startDateAs = '1970-01-01', $endDateAS = '1970-01-01')
|
||||
{
|
||||
$stmtApproval = $this->_stmtApproval($mainTable, $startDateAs, $endDateAS);
|
||||
$stmtUpdateApproval = $this->_stmtUpdateApproval($mainTable);
|
||||
$stmtUpdateNextApproval = $this->_stmtUpdateNextApproval($mainTable);
|
||||
$stmtGetLevel = $this->_stmtGetLevel($mainTable, $startDateAs, $endDateAS);
|
||||
|
||||
return [
|
||||
$stmtApproval,
|
||||
$stmtUpdateApproval,
|
||||
$stmtUpdateNextApproval,
|
||||
$stmtGetLevel
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $mainTable main table approval that will be concated with other table related to query
|
||||
* @param string $startDateAs
|
||||
* @param string $endDateAS
|
||||
*
|
||||
* @return array
|
||||
*
|
||||
* @uses getApproveDependencies
|
||||
*/
|
||||
private function getRejectDependencies($mainTable, $startDateAs = '1970-01-01', $endDateAS = '1970-01-01')
|
||||
{
|
||||
return $this->getApproveDependencies($mainTable, $startDateAs, $endDateAS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Unapprove Statement dependencies
|
||||
*
|
||||
* @param string $mainTable
|
||||
* @return array
|
||||
* [
|
||||
* $stmtCheckLast,
|
||||
* $stmtUpdateGroup,
|
||||
* $stmtUpdateLevel1,
|
||||
* $stmtUpdateOtherLevel,
|
||||
* $stmtCheckApproval
|
||||
* ]
|
||||
*
|
||||
*/
|
||||
private function getUnapproveDependencies($mainTable)
|
||||
{
|
||||
return $this->_stmtUnapproveApproval($mainTable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Unreject Statement dependencies
|
||||
*
|
||||
* @param string $mainTable
|
||||
* @return array
|
||||
* [
|
||||
* $stmtCheckLast,
|
||||
* $stmtUpdateGroup,
|
||||
* $stmtUpdateLevel1,
|
||||
* $stmtUpdateOtherLevel,
|
||||
* $stmtCheckApproval
|
||||
* ]
|
||||
*
|
||||
*/
|
||||
private function getUnrejectDependencies($mainTable)
|
||||
{
|
||||
return $this->_stmtUnrejectApproval($mainTable);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* get Employee by effective date.
|
||||
*
|
||||
* if effective date is null, it will use current date
|
||||
*
|
||||
* @param string $requestBy
|
||||
* @param string|null $effectiveDate
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function getEmployee($requestBy, $effectiveDate = null)
|
||||
{
|
||||
if ($effectiveDate == null) $effectiveDate = date('Y-m-d');
|
||||
$stmt = $this->_stmtEmployeeData();
|
||||
$stmt->bindValue(':nik', $requestBy, PDO::PARAM_STR);
|
||||
$stmt->bindValue(':effectiveDate', $effectiveDate, PDO::PARAM_STR);
|
||||
$stmt->execute();
|
||||
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
return count($rs) > 0 ? $rs[0] : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get latest approval status by transaction id
|
||||
* @param string $mainTable
|
||||
* @param mixed $transactionId
|
||||
*
|
||||
* @return array multidimentional
|
||||
*/
|
||||
private function getLatestApproval($mainTable, $transactionId)
|
||||
{
|
||||
$stmt = $this->_stmtLatestApproval($mainTable);
|
||||
$stmt->bindValue(':id', $transactionId);
|
||||
$stmt->execute();
|
||||
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
return $res;
|
||||
}
|
||||
|
||||
|
||||
private function _stmtApproval($mainTable, $startDateAs = '1970-01-01', $endDateAS = '1970-01-01')
|
||||
{
|
||||
$sql = "SELECT
|
||||
a.id,
|
||||
a.approval_status,
|
||||
a.approval_level,
|
||||
a.is_last_approval,
|
||||
IF(a.is_group='1', (
|
||||
SELECT s.nik_app
|
||||
FROM `{$mainTable}_group_approval` s
|
||||
WHERE s.`{$mainTable}_approval_id`=a.id
|
||||
AND s.nik_app=:approved_by),
|
||||
a.approved_by
|
||||
) AS approved_by,
|
||||
a.days_limit_approval,
|
||||
a.is_limit_approval,
|
||||
'$startDateAs' AS start_date,
|
||||
'$endDateAS' AS end_date
|
||||
FROM `{$mainTable}_approval` a
|
||||
LEFT JOIN `{$mainTable}` b ON a.`{$mainTable}_id` = b.id
|
||||
WHERE a.`{$mainTable}_id` = :transaction_id
|
||||
ORDER BY a.approval_level ASC";
|
||||
return $this->registry->db->prepare($sql);
|
||||
}
|
||||
|
||||
private function _stmtUpdateApproval($mainTable)
|
||||
{
|
||||
$sql = "UPDATE {$mainTable}_approval
|
||||
SET approval_status = :approval_status,
|
||||
approval_date = CURRENT_TIMESTAMP(),
|
||||
`approved_by` = :approved_by,
|
||||
reject_comment= :reject_comment
|
||||
WHERE id = :id";
|
||||
return $this->registry->db->prepare($sql);
|
||||
}
|
||||
|
||||
private function _stmtUpdateNextApproval($mainTable)
|
||||
{
|
||||
$sql = "UPDATE {$mainTable}_approval SET approval_status='1' WHERE id=:id";
|
||||
return $this->registry->db->prepare($sql);
|
||||
}
|
||||
|
||||
private function _stmtGetLevel($mainTable, $startDateAs = '1970-01-01', $endDateAS = '1970-01-01')
|
||||
{
|
||||
$sql = "SELECT approval_level FROM (
|
||||
SELECT
|
||||
a.id,
|
||||
a.approval_status,
|
||||
a.approval_level,
|
||||
a.is_last_approval,
|
||||
IF(a.is_group='1',(
|
||||
SELECT s.nik_app
|
||||
FROM `{$mainTable}_group_approval` s
|
||||
WHERE s.`{$mainTable}_approval_id`=a.id
|
||||
AND s.nik_app = :approved_by),
|
||||
a.approved_by
|
||||
) AS approved_by,
|
||||
a.days_limit_approval,
|
||||
a.is_limit_approval,
|
||||
'$startDateAs' AS start_date,
|
||||
'$endDateAS' AS end_date
|
||||
FROM `{$mainTable}_approval` a
|
||||
LEFT JOIN `{$mainTable}` b ON a.`{$mainTable}_id` = b.id
|
||||
WHERE a.`{$mainTable}_id`=:transaction_id
|
||||
) AS t
|
||||
WHERE t.approved_by = :approved_by
|
||||
ORDER BY t.approval_level ASC";
|
||||
return $this->registry->db->prepare($sql);
|
||||
}
|
||||
|
||||
|
||||
private function _stmtUnrejectApproval($mainTable)
|
||||
{
|
||||
return $this->_stmtUnapproveApproval($mainTable);
|
||||
}
|
||||
|
||||
private function _stmtUnapproveApproval($mainTable)
|
||||
{
|
||||
$sqlIsLastApproval = "SELECT COUNT(id) AS total FROM {$mainTable}_approval
|
||||
WHERE {$mainTable}_id=:transaction_id
|
||||
AND is_last_approval='1'
|
||||
AND approval_status='2'";
|
||||
|
||||
$sqlCheck = "SELECT COUNT(a.id) AS total FROM {$mainTable}_approval a
|
||||
WHERE a.{$mainTable}_id=:transaction_id
|
||||
AND (a.approved_by=:approved_by OR :approved_by IN (
|
||||
SELECT s.nik_app FROM {$mainTable}_group_approval s
|
||||
WHERE s.{$mainTable}_approval_id=a.id
|
||||
)
|
||||
)";
|
||||
$sqlUpdateGroup = "UPDATE {$mainTable}_approval SET approved_by='-' WHERE {$mainTable}_id=:transaction_id AND is_group='1'";
|
||||
$sqlUpdateLevel1 = "UPDATE {$mainTable}_approval SET approval_status='1' WHERE {$mainTable}_id=:transaction_id AND approval_level=1 ";
|
||||
$sqlUpdateOther = "UPDATE {$mainTable}_approval SET approval_status='0' WHERE {$mainTable}_id=:transaction_id AND approval_level>1 ";
|
||||
|
||||
$stmtCheckLast = $this->registry->db->prepare($sqlIsLastApproval);
|
||||
$stmtUpdateGroup = $this->registry->db->prepare($sqlUpdateGroup);
|
||||
$stmtUpdateLevel1 = $this->registry->db->prepare($sqlUpdateLevel1);
|
||||
$stmtUpdateOtherLevel = $this->registry->db->prepare($sqlUpdateOther);
|
||||
$stmtCheckApproval = $this->registry->db->prepare($sqlCheck);
|
||||
|
||||
return array(
|
||||
$stmtCheckLast,
|
||||
$stmtUpdateGroup,
|
||||
$stmtUpdateLevel1,
|
||||
$stmtUpdateOtherLevel,
|
||||
$stmtCheckApproval
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
private function _stmtApprovalSetApproval($mainTable)
|
||||
{
|
||||
$sql = "INSERT INTO `{$mainTable}_approval` (
|
||||
`approval_level`,
|
||||
`approval_status`,
|
||||
`approval_type`,
|
||||
`approved_by`,
|
||||
`{$mainTable}_id`,
|
||||
`is_group`,
|
||||
`is_last_approval`,
|
||||
`is_limit_approval`,
|
||||
`days_limit_approval`)
|
||||
VALUES (
|
||||
:approval_level,
|
||||
:approval_status,
|
||||
:approval_type,
|
||||
:approved_by,
|
||||
:transaction_id,
|
||||
:is_group,
|
||||
:is_last_approval,
|
||||
:is_limit_approval,
|
||||
:days_limit_approval
|
||||
);";
|
||||
return $this->registry->db->prepare($sql);
|
||||
}
|
||||
|
||||
private function _stmtGroupApproval($mainTable)
|
||||
{
|
||||
$sql = "INSERT INTO {$mainTable}_group_approval ({$mainTable}_approval_id, nik_app)
|
||||
VALUES (:emp_absence_approval_id, :nik_app )";
|
||||
return $this->registry->db->prepare($sql);
|
||||
}
|
||||
|
||||
private function _stmtEmployeeData()
|
||||
{
|
||||
$sql = "SELECT
|
||||
SUBSTRING(a.grade,1,1) AS grade,
|
||||
b.sub_area_id,
|
||||
c.company_id,
|
||||
c.country_id,
|
||||
ol.`bt_code`,
|
||||
ol.abreviation as positionID,
|
||||
getEmpJobtitle(a.nik,:effectiveDate) as job_title_name
|
||||
FROM employement a
|
||||
LEFT JOIN `emp_job` ej ON a.nik=ej.nik
|
||||
AND ej.`effective_date`=(SELECT ej1.`effective_date` FROM `emp_job` ej1 WHERE ej1.nik=a.nik AND ej1.`effective_date` <=:effectiveDate ORDER BY ej1.`effective_date` DESC LIMIT 1)
|
||||
INNER JOIN `mpp_detail` md on ej.`mpp_detail_id`=md.id
|
||||
INNER JOIN org_layer ol on md.org_layer_id=ol.id
|
||||
INNER JOIN emp_personal_sub_area b ON a.nik=b.nik
|
||||
AND b.effective_date=(SELECT s.effective_date FROM emp_personal_sub_area s
|
||||
WHERE s.nik=a.nik AND s.`effective_date` <=:effectiveDate ORDER BY s.`effective_date` DESC LIMIT 1)
|
||||
INNER JOIN sub_area c ON b.sub_area_id=c.id
|
||||
WHERE a.`nik`=:nik";
|
||||
|
||||
return $this->registry->db->prepare($sql);
|
||||
}
|
||||
|
||||
|
||||
private function _stmtLatestApproval($mainTable)
|
||||
{
|
||||
$sql = "SELECT a.id,
|
||||
getEmpName(a.approved_by) AS name,
|
||||
CASE WHEN approval_status='1' THEN
|
||||
CONCAT_WS(' ','Waiting Approval', a.approved_by,'-',getEmpName(a.approved_by),'(',UPPER(a.approval_type),')')
|
||||
WHEN approval_status='2' THEN
|
||||
CONCAT_WS(' ','Approved By', a.approved_by,'-',getEmpName(a.approved_by),'(',UPPER(a.approval_type),')')
|
||||
WHEN approval_status='4' THEN
|
||||
CONCAT_WS(' ','Rejected By', a.approved_by,'-',getEmpName(a.approved_by),'(',UPPER(a.approval_type),')')
|
||||
END AS types,
|
||||
reject_comment AS rejected_comment,
|
||||
approval_status
|
||||
FROM {$mainTable}_approval a
|
||||
WHERE a.{$mainTable}_id=:id AND approval_status != '0'
|
||||
ORDER BY a.id DESC LIMIT 1";
|
||||
return $this->registry->db->prepare($sql);
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
59
Aiko/Aiko/Libs/ApprovalRequest/HasApprovalRequest.php
Normal file
59
Aiko/Aiko/Libs/ApprovalRequest/HasApprovalRequest.php
Normal file
@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
/**
|
||||
* @property ApprovalRequest $approvalRequest
|
||||
*/
|
||||
trait HasApprovalRequest
|
||||
{
|
||||
public function batchApprove($requestBy, $transactionIds = [])
|
||||
{
|
||||
return $this->approvalRequest->batchApprove($requestBy, $transactionIds);
|
||||
}
|
||||
|
||||
public function batchReject($requestBy, $transactionIds = [], $comment = '')
|
||||
{
|
||||
return $this->approvalRequest->batchReject($requestBy, $transactionIds, $comment);
|
||||
}
|
||||
|
||||
public function batchUnapprove($requestBy, $transactionIds = [])
|
||||
{
|
||||
return $this->approvalRequest->batchUnapprove($requestBy, $transactionIds);
|
||||
}
|
||||
|
||||
public function batchUnreject($requestBy, $transactionIds = [])
|
||||
{
|
||||
return $this->approvalRequest->batchUnreject($requestBy, $transactionIds);
|
||||
}
|
||||
|
||||
public function approve($requestBy, $transactionId)
|
||||
{
|
||||
return $this->approvalRequest->approve($requestBy, $transactionId);
|
||||
}
|
||||
|
||||
public function reject($requestBy, $transactionId, $notes = '')
|
||||
{
|
||||
return $this->approvalRequest->reject($requestBy, $transactionId, $notes);
|
||||
}
|
||||
|
||||
public function unapprove($requestBy, $transactionId)
|
||||
{
|
||||
return $this->approvalRequest->unApprove($requestBy, $transactionId);
|
||||
}
|
||||
|
||||
public function unreject($requestBy, $transactionId)
|
||||
{
|
||||
return $this->unapprove($requestBy, $transactionId);
|
||||
}
|
||||
|
||||
public function latestApproval($transactionId)
|
||||
{
|
||||
return $this->approvalRequest->latestApproval($transactionId);
|
||||
}
|
||||
|
||||
public function infoApproval($transactionId)
|
||||
{
|
||||
return $this->approvalRequest->infoApproval($transactionId);
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
274
Aiko/Aiko/Libs/ApprovalRequest/WithApprovalRequest.php
Normal file
274
Aiko/Aiko/Libs/ApprovalRequest/WithApprovalRequest.php
Normal file
@ -0,0 +1,274 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
/** @property ApprovalRequest $obj */
|
||||
trait WithApprovalRequest
|
||||
{
|
||||
/**
|
||||
* approve
|
||||
*
|
||||
* @param Object $oJson
|
||||
*
|
||||
* expected data property exist in object
|
||||
* $oJson->data payload needed
|
||||
* [
|
||||
* ['id' => 1]
|
||||
* ]
|
||||
*
|
||||
**/
|
||||
private function approve($oJson)
|
||||
{
|
||||
$requestBy = \Helper::getSessionVar('username');
|
||||
$transactionIds = \Helper::getArrayValueByKey($oJson->data);
|
||||
if (count($transactionIds) == 0) {
|
||||
Http::ErrorQueryResponse([
|
||||
'pesan' => 'Data is empty',
|
||||
'token' => $_SESSION['token']
|
||||
], 'json');
|
||||
}
|
||||
$result = $this->obj->approve($requestBy, $transactionIds[0]);
|
||||
if ($result['isSuccess'] == 0) {
|
||||
Http::ErrorQueryResponse([
|
||||
'pesan' => 'Failed Approve Request',
|
||||
'token' => $_SESSION['token']
|
||||
], 'json');
|
||||
}
|
||||
Http::ResponseJson(array(
|
||||
'pesan' => 'Success Approve Request',
|
||||
'token' => $_SESSION['token']
|
||||
), '1');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* reject
|
||||
*
|
||||
* @param Object $oJson
|
||||
*
|
||||
* expected data property exist in object
|
||||
* $oJson->data payload needed
|
||||
* [
|
||||
* ['id' => 1]
|
||||
* ]
|
||||
*
|
||||
**/
|
||||
private function reject($oJson)
|
||||
{
|
||||
$requestBy = \Helper::getSessionVar('username');
|
||||
$transactionIds = \Helper::getArrayValueByKey($oJson->data);
|
||||
if (count($transactionIds) == 0) {
|
||||
Http::ErrorQueryResponse([
|
||||
'pesan' => 'Data is empty',
|
||||
'token' => $_SESSION['token']
|
||||
], 'json');
|
||||
}
|
||||
$result = $this->obj->reject($requestBy, $transactionIds[0]);
|
||||
if ($result['isSuccess'] == 0) {
|
||||
Http::ErrorQueryResponse([
|
||||
'pesan' => 'Failed Reject Request',
|
||||
'token' => $_SESSION['token']
|
||||
], 'json');
|
||||
}
|
||||
Http::ResponseJson(array(
|
||||
'pesan' => 'Success Reject Request',
|
||||
'token' => $_SESSION['token']
|
||||
), '1');
|
||||
}
|
||||
|
||||
/**
|
||||
* unapprove
|
||||
*
|
||||
* @param Object $oJson
|
||||
*
|
||||
* expected data property exist in object
|
||||
* $oJson->data payload needed
|
||||
* [
|
||||
* ['id' => 1]
|
||||
* ]
|
||||
*
|
||||
**/
|
||||
private function unapprove($oJson)
|
||||
{
|
||||
$requestBy = \Helper::getSessionVar('username');
|
||||
$transactionIds = \Helper::getArrayValueByKey($oJson->data);
|
||||
if (count($transactionIds) == 0) {
|
||||
Http::ErrorQueryResponse([
|
||||
'pesan' => 'Data is empty',
|
||||
'token' => $_SESSION['token']
|
||||
], 'json');
|
||||
}
|
||||
$result = $this->obj->unapprove($requestBy, $transactionIds[0]);
|
||||
if ($result['isSuccess'] == 0) {
|
||||
Http::ErrorQueryResponse([
|
||||
'pesan' => 'Failed Un-Approve Request',
|
||||
'token' => $_SESSION['token']
|
||||
], 'json');
|
||||
}
|
||||
Http::ResponseJson(array(
|
||||
'pesan' => 'Success Un-Approve Request',
|
||||
'token' => $_SESSION['token']
|
||||
), '1');
|
||||
}
|
||||
|
||||
/**
|
||||
* unreject
|
||||
*
|
||||
* @param Object $oJson
|
||||
*
|
||||
* expected data property exist in object
|
||||
* $oJson->data payload needed
|
||||
* [
|
||||
* ['id' => 1]
|
||||
* ]
|
||||
*
|
||||
**/
|
||||
private function unreject($oJson)
|
||||
{
|
||||
$requestBy = \Helper::getSessionVar('username');
|
||||
$transactionIds = \Helper::getArrayValueByKey($oJson->data);
|
||||
if (count($transactionIds) == 0) {
|
||||
Http::ErrorQueryResponse([
|
||||
'pesan' => 'Data is empty',
|
||||
'token' => $_SESSION['token']
|
||||
], 'json');
|
||||
}
|
||||
$result = $this->obj->unreject($requestBy, $transactionIds[0]);
|
||||
if ($result['isSuccess'] == 0) {
|
||||
Http::ErrorQueryResponse([
|
||||
'pesan' => 'Failed Un-Reject Request',
|
||||
'token' => $_SESSION['token']
|
||||
], 'json');
|
||||
}
|
||||
Http::ResponseJson(array(
|
||||
'pesan' => 'Success Un-Reject Request',
|
||||
'token' => $_SESSION['token']
|
||||
), '1');
|
||||
}
|
||||
|
||||
/**
|
||||
* Batch approve
|
||||
*
|
||||
* Undocumented function long description
|
||||
*
|
||||
* @param Object $oJson
|
||||
*
|
||||
* expected data property exist in object
|
||||
* $oJson->data payload needed
|
||||
* [
|
||||
* ['id' => 1]
|
||||
* ]
|
||||
*
|
||||
**/
|
||||
private function batchApprove($oJson)
|
||||
{
|
||||
$requestBy = \Helper::getSessionVar('username');
|
||||
$transactionIds = \Helper::getArrayValueByKey($oJson->data);
|
||||
if (count($transactionIds) == 0) {
|
||||
Http::ErrorQueryResponse([
|
||||
'pesan' => 'Data is empty',
|
||||
'token' => $_SESSION['token']
|
||||
], 'json');
|
||||
}
|
||||
$result = $this->obj->batchApprove($requestBy, $transactionIds);
|
||||
$response = array(
|
||||
'pesan' => 'Approve data completed, Success: ' . count($result['success']) . ', Failed: ' . count($result['failed']),
|
||||
'moreInfo' => $result,
|
||||
'token' => $_SESSION['token']
|
||||
);
|
||||
Http::ResponseJson($response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Batch unapprove
|
||||
*
|
||||
* @param Object $oJson
|
||||
*
|
||||
* expected data property exist in object
|
||||
* $oJson->data payload needed
|
||||
* [
|
||||
* ['id' => 1]
|
||||
* ]
|
||||
*
|
||||
**/
|
||||
private function batchUnapprove($oJson)
|
||||
{
|
||||
$requestBy = \Helper::getSessionVar('username');
|
||||
$transactionIds = \Helper::getArrayValueByKey($oJson->data);
|
||||
if (count($transactionIds) == 0) {
|
||||
Http::ErrorQueryResponse([
|
||||
'pesan' => 'Data is empty',
|
||||
'token' => $_SESSION['token']
|
||||
], 'json');
|
||||
}
|
||||
$result = $this->obj->batchUnapprove($requestBy, $transactionIds);
|
||||
$response = array(
|
||||
'pesan' => 'Un-Approve data completed, Success: ' . count($result['success']) . ', Failed: ' . count($result['failed']),
|
||||
'moreInfo' => $result,
|
||||
'token' => $_SESSION['token']
|
||||
);
|
||||
Http::ResponseJson($response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Batch reject
|
||||
*
|
||||
* @param Object $oJson
|
||||
*
|
||||
* expected data property exist in object
|
||||
* $oJson->data payload needed
|
||||
* [
|
||||
* ['id' => 1]
|
||||
* ]
|
||||
*
|
||||
**/
|
||||
private function batchReject($oJson)
|
||||
{
|
||||
$requestBy = \Helper::getSessionVar('username');
|
||||
$transactionIds = \Helper::getArrayValueByKey($oJson->data);
|
||||
if (count($transactionIds) == 0) {
|
||||
Http::ErrorQueryResponse([
|
||||
'pesan' => 'Data is empty',
|
||||
'token' => $_SESSION['token']
|
||||
], 'json');
|
||||
}
|
||||
$result = $this->obj->batchReject($requestBy, $transactionIds, $oJson->comment);
|
||||
$response = array(
|
||||
'pesan' => 'Reject data completed, Success: ' . count($result['success']) . ', Failed: ' . count($result['failed']),
|
||||
'moreInfo' => $result,
|
||||
'token' => $_SESSION['token']
|
||||
);
|
||||
Http::ResponseJson($response, '1');
|
||||
}
|
||||
|
||||
/**
|
||||
* Batch unreject
|
||||
*
|
||||
* @param Object $oJson
|
||||
*
|
||||
* expected data property exist in object
|
||||
* $oJson->data payload needed
|
||||
* [
|
||||
* ['id' => 1]
|
||||
* ]
|
||||
*
|
||||
**/
|
||||
private function batchUnreject($oJson)
|
||||
{
|
||||
$requestBy = \Helper::getSessionVar('username');
|
||||
$transactionIds = \Helper::getArrayValueByKey($oJson->data);
|
||||
if (count($transactionIds) == 0) {
|
||||
Http::ErrorQueryResponse([
|
||||
'pesan' => 'Data is empty',
|
||||
'token' => $_SESSION['token']
|
||||
], 'json');
|
||||
}
|
||||
$result = $this->obj->batchUnapprove($requestBy, $transactionIds);
|
||||
$response = array(
|
||||
'pesan' => 'Approve data completed, Success: ' . count($result['success']) . ', Failed: ' . count($result['failed']),
|
||||
'moreInfo' => $result,
|
||||
'token' => $_SESSION['token']
|
||||
);
|
||||
Http::ResponseJson($response);
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
105
Aiko/Aiko/Libs/Debug.php
Normal file
105
Aiko/Aiko/Libs/Debug.php
Normal file
@ -0,0 +1,105 @@
|
||||
<?php
|
||||
namespace Aiko;
|
||||
class Debug{
|
||||
|
||||
private static $firephp = NULL;
|
||||
private static $env=NULL;
|
||||
public function __construct($env) {
|
||||
self::$env=$env;
|
||||
if(self::$env==='developer'){
|
||||
self::$firephp = \FirePHP::getInstance(true);
|
||||
}
|
||||
}
|
||||
public function info($content,$label='')
|
||||
{
|
||||
if(self::$env==='developer')
|
||||
{
|
||||
if($label=='')
|
||||
{
|
||||
self::$firephp->fb($content,\FirePHP::INFO);
|
||||
}else
|
||||
{
|
||||
self::$firephp->fb($content,$label,\FirePHP::INFO);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
public function log($content,$label='')
|
||||
{
|
||||
if(self::$env==='developer')
|
||||
{
|
||||
if($label=='')
|
||||
{
|
||||
self::$firephp->fb($content,\FirePHP::LOG);
|
||||
}else
|
||||
{
|
||||
self::$firephp->fb($content,$label,\FirePHP::LOG);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
public function warning($content,$label='')
|
||||
{
|
||||
if(self::$env==='developer')
|
||||
{
|
||||
if($label=='')
|
||||
{
|
||||
self::$firephp->fb($content,\FirePHP::WARN);
|
||||
}else
|
||||
{
|
||||
self::$firephp->fb($content,$label,\FirePHP::WARN);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
public function error($content,$label='')
|
||||
{
|
||||
if(self::$env==='developer')
|
||||
{
|
||||
if($label=='')
|
||||
{
|
||||
self::$firephp->fb($content,\FirePHP::ERROR);
|
||||
}else
|
||||
{
|
||||
self::$firephp->fb($content,$label,\FirePHP::ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
public function trace($label)
|
||||
{
|
||||
if(self::$env==='developer')
|
||||
{
|
||||
self::$firephp->fb($label,\FirePHP::TRACE);
|
||||
}
|
||||
}
|
||||
|
||||
public function table($content,$label='')
|
||||
{
|
||||
if(self::$env==='developer')
|
||||
{
|
||||
if($label=='')
|
||||
{
|
||||
self::$firephp->fb($content,\FirePHP::TABLE);
|
||||
}else
|
||||
{
|
||||
self::$firephp->fb($content,$label,\FirePHP::TABLE);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
public function dump($content,$label='')
|
||||
{
|
||||
if(self::$env==='developer')
|
||||
{
|
||||
if($label=='')
|
||||
{
|
||||
self::$firephp->fb($content,\FirePHP::DUMP);
|
||||
}else
|
||||
{
|
||||
self::$firephp->fb($content,$label,\FirePHP::DUMP);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
private function __clone(){}
|
||||
}
|
3
Aiko/Aiko/Libs/Debug.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/Debug.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
104
Aiko/Aiko/Libs/FCM.php
Normal file
104
Aiko/Aiko/Libs/FCM.php
Normal file
@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
use PDO;
|
||||
|
||||
class FCM
|
||||
{
|
||||
const dashboard = '/dashboard';
|
||||
const login = '/login';
|
||||
const approvalAbnormal = '/approval_abnormal';
|
||||
const approvalAbsence = '/approval_absence';
|
||||
const approvalChangeShift = '/approval_change_shift';
|
||||
const approvalOvertime = '/approval_overtime';
|
||||
const approvalReplacementDay = 'approval_replacement_day';
|
||||
const approvalUpdateFinger = '/approval_update_finger';
|
||||
protected $registry;
|
||||
|
||||
public function __construct($registry)
|
||||
{
|
||||
$this->registry = $registry;
|
||||
}
|
||||
|
||||
private $fcmUrl = "https://fcm.googleapis.com/fcm/send";
|
||||
|
||||
public function sendPushNotificationByEmpId($empId, $title, $message, $screen = '/dashboard')
|
||||
{
|
||||
$sqlCheck = "SELECT id, token FROM fcm_token WHERE emp_id = :emp_id";
|
||||
$stmtCheck = $this->registry->db->prepare($sqlCheck);
|
||||
$stmtCheck->bindValue(':emp_id', $empId, PDO::PARAM_INT);
|
||||
$stmtCheck->execute();
|
||||
$rsCheck = $stmtCheck->fetchAll(PDO::FETCH_ASSOC);
|
||||
$ctr = count($rsCheck);
|
||||
|
||||
if ($ctr === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$response = [];
|
||||
$toTokens = [];
|
||||
|
||||
for ($i = 0; $i < $ctr; $i++) {
|
||||
array_push($toTokens, $rsCheck[$i]['token']);
|
||||
}
|
||||
|
||||
$stmtDelete = $this->registry->db->prepare('delete from fcm_token where id = :id');
|
||||
$temp = $this->sendPushNotification($toTokens, $title, $message, $empId, $screen);
|
||||
$dcode = json_decode($temp, true);
|
||||
for ($i = 0; $i < count($dcode['results']); $i++) {
|
||||
$status = [
|
||||
'is_send' => true,
|
||||
'is_deleted' => false,
|
||||
'fcm_token_id' => $rsCheck[$i]['id'],
|
||||
'emp_id' => $empId
|
||||
];
|
||||
if (isset($dcode['results'][$i]['error']) && $dcode['results'][$i]['error'] === 'NotRegistered') {
|
||||
$stmtDelete->bindValue(':id', $rsCheck[$i]['id'], PDO::PARAM_INT);
|
||||
$stmtDelete->execute();
|
||||
$status['is_send'] = false;
|
||||
$status['is_deleted'] = true;
|
||||
}
|
||||
array_push($response, $status);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function sendPushNotification($toToken = [], $title, $message, $userId = null, $screen = '/dashboard')
|
||||
{
|
||||
$header = [
|
||||
'authorization: key=' . $this->registry->config->fcm_token,
|
||||
'content-type: application/json',
|
||||
];
|
||||
|
||||
$notification = [
|
||||
'title' => $title,
|
||||
'body' => $message,
|
||||
"click_action" => 'FLUTTER_NOTIFICATION_CLICK',
|
||||
];
|
||||
$extraNotificationData = [
|
||||
'screen' => $screen,
|
||||
"message" => $notification,
|
||||
"id" => $userId,
|
||||
];
|
||||
$fcmNotification = [
|
||||
'registration_ids' => $toToken,
|
||||
'notification' => $notification,
|
||||
'data' => $extraNotificationData,
|
||||
];
|
||||
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_URL, $this->fcmUrl);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
|
||||
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
|
||||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification));
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
|
||||
|
||||
$result = curl_exec($ch);
|
||||
curl_close($ch);
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
3
Aiko/Aiko/Libs/FCM.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/FCM.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
89
Aiko/Aiko/Libs/GeoTz.php
Normal file
89
Aiko/Aiko/Libs/GeoTz.php
Normal file
@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
use DateTime;
|
||||
use DateTimeZone;
|
||||
use ErrorException;
|
||||
use PDO;
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Exception\ClientException;
|
||||
|
||||
class GeoTz
|
||||
{
|
||||
protected $registry;
|
||||
|
||||
private $endpoint;
|
||||
|
||||
private $apiKey;
|
||||
|
||||
private $client;
|
||||
|
||||
public function __construct($registry)
|
||||
{
|
||||
$this->registry = $registry;
|
||||
$this->endpoint = $this->registry->config->api_geo_tz_endpoint;
|
||||
$this->apiKey = $this->registry->config->api_geo_tz_key;
|
||||
$this->client = new Client([
|
||||
'base_uri' => $this->endpoint,
|
||||
'http_errors ' => false,
|
||||
'headers' => [
|
||||
'Content-Type' => 'application/json',
|
||||
'Accept' => 'application/json',
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
public function getCoordinateTimezone($lat, $lon)
|
||||
{
|
||||
return $this->getTimezoneApi($lat, $lon);
|
||||
}
|
||||
|
||||
public function getTimezoneLocally($hourOffset)
|
||||
{
|
||||
$sign = $hourOffset < 0 ? '-' : '+';
|
||||
$date = new DateTime('now', new DateTimeZone($sign . abs($hourOffset)));
|
||||
return array(
|
||||
'date' => $date->format('Y-m-d'),
|
||||
'time' => $date->format('H:i:s'),
|
||||
'date_time' => $date->format('Y-m-d H:i:s'),
|
||||
'api' => []
|
||||
);
|
||||
}
|
||||
|
||||
private function getTimezoneApi($lat, $lon)
|
||||
{
|
||||
try {
|
||||
|
||||
$response = $this->client->get('/timezone', [
|
||||
'query' => [
|
||||
'apiKey' => $this->apiKey,
|
||||
'lat' => $lat,
|
||||
'long' => $lon
|
||||
]
|
||||
]);
|
||||
|
||||
if ($response->getStatusCode() !== 200) {
|
||||
throw new ErrorException((string) $response->getBody()->getContents());
|
||||
}
|
||||
|
||||
$data = $response->getBody()->getContents();
|
||||
$tz = json_decode($data, true);
|
||||
$date = new DateTime('now', new DateTimeZone($tz['timezone']));
|
||||
|
||||
return array(
|
||||
'date' => $date->format('Y-m-d'),
|
||||
'time' => $date->format('H:i:s'),
|
||||
'date_time' => $date->format('Y-m-d H:i:s')
|
||||
);
|
||||
} catch (ErrorException $e) {
|
||||
$this->registry
|
||||
->log
|
||||
->error('Geolocation / getTimezoneApi :'
|
||||
. $e->getMessage() . ', Line: '
|
||||
. $e->getLine() . ', File: '
|
||||
. $e->getFile());
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
3
Aiko/Aiko/Libs/GeoTz.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/GeoTz.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
346
Aiko/Aiko/Libs/Http.php
Normal file
346
Aiko/Aiko/Libs/Http.php
Normal file
@ -0,0 +1,346 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
use Firebase\JWT\JWT;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use finfo;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
class Http
|
||||
{
|
||||
private static $request = null;
|
||||
private static $response = null;
|
||||
public static function GetBodyRequest()
|
||||
{
|
||||
self::$request = new Request();
|
||||
|
||||
return self::$request->getContent();
|
||||
}
|
||||
|
||||
public static function enabledCors()
|
||||
{
|
||||
// // Allow from any origin
|
||||
if (isset($_SERVER['HTTP_ORIGIN'])) {
|
||||
// Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
|
||||
// you want to allow, and if so:
|
||||
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
|
||||
header('Access-Control-Allow-Credentials: true');
|
||||
header('Access-Control-Max-Age: 86400'); // cache for 1 day
|
||||
}
|
||||
|
||||
// Access-Control headers are received during OPTIONS requests
|
||||
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
|
||||
|
||||
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
|
||||
// may also be using PUT, PATCH, HEAD etc
|
||||
{
|
||||
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
|
||||
}
|
||||
|
||||
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
|
||||
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
|
||||
}
|
||||
|
||||
exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
public static function UnauthorizedResponse($content)
|
||||
{
|
||||
self::$response = new Response(
|
||||
$content,
|
||||
Response::HTTP_UNAUTHORIZED,
|
||||
array('content-type' => 'text/html')
|
||||
);
|
||||
self::$response->headers->set('Access-Control-Allow-Origin', '*');
|
||||
self::$response->send();
|
||||
exit();
|
||||
}
|
||||
|
||||
public static function InternalServerError($content)
|
||||
{
|
||||
self::$response = new Response(
|
||||
$content,
|
||||
Response::HTTP_INTERNAL_SERVER_ERROR,
|
||||
array('content-type' => 'text/html')
|
||||
);
|
||||
self::$response->send();
|
||||
exit();
|
||||
}
|
||||
|
||||
public static function UnauthorizedResponseJson($content)
|
||||
{
|
||||
self::$response = new Response(
|
||||
JWT::jsonEncode($content),
|
||||
Response::HTTP_UNAUTHORIZED,
|
||||
array('content-type' => 'application/json')
|
||||
);
|
||||
self::$response->headers->set('Access-Control-Allow-Origin', '*');
|
||||
self::$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
|
||||
self::$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With,x-firephp,x-firephp-version,x-wf-max-combined-size');
|
||||
self::$response->send();
|
||||
exit();
|
||||
}
|
||||
public static function PageNotFound($content)
|
||||
{
|
||||
self::$response = new Response(
|
||||
$content,
|
||||
Response::HTTP_NOT_FOUND,
|
||||
array('content-type' => 'text/html')
|
||||
);
|
||||
self::$response->headers->set('Access-Control-Allow-Origin', '*');
|
||||
self::$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
|
||||
self::$response->headers->set('Access-Control-Allow-Headers', 'Content-Type,Authorization,X-Requested-With,x-firephp,x-firephp-version,x-wf-max-combined-size');
|
||||
self::$response->send();
|
||||
|
||||
exit();
|
||||
}
|
||||
|
||||
public static function GetXsrfHeader()
|
||||
{
|
||||
self::$request = Request::CreateFromGlobals();
|
||||
$token = self::$request->headers->get('X-XSRF-TOKEN');
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
public static function GetTokenHeader()
|
||||
{
|
||||
self::$request = Request::CreateFromGlobals();
|
||||
$token = self::$request->headers->get('token');
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
public static function ErrorQueryResponse($content, $type = 'text')
|
||||
{
|
||||
if ($type == 'text') {
|
||||
self::$response = new Response(
|
||||
$content,
|
||||
Response::HTTP_BAD_REQUEST,
|
||||
array('content-type' => 'text/html')
|
||||
);
|
||||
self::$response->send();
|
||||
} else {
|
||||
self::$response = new JsonResponse();
|
||||
self::$response->setData($content);
|
||||
self::$response->headers->set('Access-Control-Allow-Origin', '*');
|
||||
self::$response->setStatusCode(Response::HTTP_BAD_REQUEST);
|
||||
self::$response->send();
|
||||
}
|
||||
|
||||
exit();
|
||||
}
|
||||
|
||||
public static function Forbidden($content, $type = 'text')
|
||||
{
|
||||
if ($type == 'text') {
|
||||
self::$response = new Response(
|
||||
$content,
|
||||
Response::HTTP_FORBIDDEN,
|
||||
array('content-type' => 'text/html')
|
||||
);
|
||||
self::$response->send();
|
||||
} else {
|
||||
self::$response = new JsonResponse();
|
||||
self::$response->setData($content);
|
||||
self::$response->headers->set('Access-Control-Allow-Origin', '*');
|
||||
self::$response->setStatusCode(Response::HTTP_FORBIDDEN);
|
||||
self::$response->send();
|
||||
}
|
||||
|
||||
exit();
|
||||
}
|
||||
|
||||
public static function responseJson($array, $secure = '0', $cors = '0')
|
||||
{
|
||||
if ($secure == '0') {
|
||||
self::$response = new JsonResponse();
|
||||
self::$response->setData($array);
|
||||
if ($cors == '1') {
|
||||
self::$response->headers->set('Access-Control-Allow-Origin', '*');
|
||||
self::$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With,x-firephp-version,x-firephp,x-firephp-version,x-wf-max-combined-size');
|
||||
self::$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
|
||||
}
|
||||
self::$response->send();
|
||||
} else {
|
||||
self::$response = new Response();
|
||||
$jtext = ")]}',\n" . JWT::jsonEncode($array, JSON_UNESCAPED_SLASHES);
|
||||
self::$response->setContent($jtext);
|
||||
self::$response->headers->set('Content-Type', 'application/json');
|
||||
if ($cors == '1') {
|
||||
self::$response->headers->set('Access-Control-Allow-Origin', '*');
|
||||
}
|
||||
self::$response->send();
|
||||
}
|
||||
|
||||
exit();
|
||||
}
|
||||
|
||||
public static function GetVarData($key, $method = 'get')
|
||||
{
|
||||
self::$request = Request::createFromGlobals();
|
||||
if ($method == 'get') {
|
||||
$result = self::$request->query->get($key);
|
||||
} else {
|
||||
|
||||
$result = self::$request->request->get($key);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public static function Error404($content)
|
||||
{
|
||||
self::$response = new Response(
|
||||
$content,
|
||||
Response::HTTP_NOT_FOUND,
|
||||
array('content-type' => 'text/html')
|
||||
);
|
||||
self::$response->send();
|
||||
exit();
|
||||
}
|
||||
|
||||
public static function GetFile($key)
|
||||
{
|
||||
|
||||
|
||||
self::$request = Request::createFromGlobals();
|
||||
// var_dump(self::$request);
|
||||
$result = self::$request->files->get($key);
|
||||
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public static function CekTokenHeader()
|
||||
{
|
||||
self::$request = Request::CreateFromGlobals();
|
||||
$token = self::$request->headers->get('token');
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
public static function CekTokenAuthHeader()
|
||||
{
|
||||
self::$request = Request::CreateFromGlobals();
|
||||
$token = self::$request->headers->get('tokenAuth');
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
public static function getTokenJWT()
|
||||
{
|
||||
self::$request = Request::CreateFromGlobals();
|
||||
$authHeader = self::$request->headers->get('Authorization');
|
||||
list($jwt) = sscanf($authHeader, 'Bearer %s');
|
||||
// var_dump($jwt);
|
||||
return $jwt;
|
||||
}
|
||||
|
||||
public static function getBasicAuth()
|
||||
{
|
||||
self::$request = Request::CreateFromGlobals();
|
||||
$authHeader = self::$request->headers->get('Authorization');
|
||||
list($code) = sscanf($authHeader, 'Basic %s');
|
||||
// var_dump($code);
|
||||
return $code;
|
||||
}
|
||||
|
||||
public static function requestServer($key)
|
||||
{
|
||||
if (is_null(self::$request)) {
|
||||
self::$request = Request::CreateFromGlobals();
|
||||
}
|
||||
|
||||
return self::$request->server->get($key);
|
||||
}
|
||||
public static function tokenExpired($content)
|
||||
{
|
||||
$response = new Response(
|
||||
JWT::jsonEncode($content),
|
||||
Response::HTTP_NOT_ACCEPTABLE,
|
||||
array('content-type' => 'application/json')
|
||||
);
|
||||
$response->headers->set('Access-Control-Allow-Origin', '*');
|
||||
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
|
||||
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With,x-firephp,x-firephp-version,x-wf-max-combined-size');
|
||||
$response->send();
|
||||
exit();
|
||||
}
|
||||
|
||||
public static function responseFile($params)
|
||||
{
|
||||
$path_to_zip=$params['file_path'];
|
||||
|
||||
|
||||
// if( file_exists( $path_to_zip ) )
|
||||
// {
|
||||
// die();
|
||||
// header( 'Cache-Control: public' );
|
||||
// header( 'Content-Description: File Transfer' );
|
||||
// header( "Content-Disposition: attachment; filename={$path_to_zip}" );
|
||||
// header( 'Content-Type: application/zip' );
|
||||
// header( 'Content-Transfer-Encoding: binary' );
|
||||
// readfile( $path_to_zip );
|
||||
// exit;
|
||||
// }
|
||||
|
||||
// die( "ERROR: invalid song or you don't have permissions to download it." );
|
||||
$extension = pathinfo(parse_url($path_to_zip, PHP_URL_PATH), PATHINFO_EXTENSION);
|
||||
$file_info = new finfo(FILEINFO_MIME_TYPE);
|
||||
$mime_type = $file_info->buffer(file_get_contents($path_to_zip));
|
||||
$file=file_get_contents($path_to_zip);
|
||||
|
||||
$response = new Response(
|
||||
$file,
|
||||
Response::HTTP_OK,
|
||||
array('content-type' => $mime_type)
|
||||
);
|
||||
$response->send();
|
||||
|
||||
// var_dump($file);die();
|
||||
}
|
||||
|
||||
|
||||
public static function getHeaderValue($key, $default = null)
|
||||
{
|
||||
self::$request = Request::CreateFromGlobals();
|
||||
if (!self::$request->headers->has($key)) {
|
||||
return $default;
|
||||
}
|
||||
$value = self::$request->headers->has($key);
|
||||
return $value;
|
||||
}
|
||||
|
||||
public static function getAllRequest($method = 'get')
|
||||
{
|
||||
self::$request = Request::createFromGlobals();
|
||||
if ($method == 'get') {
|
||||
$result = self::$request->query->all();
|
||||
} else {
|
||||
$result = self::$request->request->all();
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
public static function isMultipartFormData()
|
||||
{
|
||||
$req = Request::CreateFromGlobals();
|
||||
$multipart=$req->headers->has('Content-Type');
|
||||
if($multipart)
|
||||
{
|
||||
$contentType=$req->headers->get('Content-Type');
|
||||
if(strpos($contentType,'multipart/form-data')!==false)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
3
Aiko/Aiko/Libs/Http.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/Http.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
143
Aiko/Aiko/Libs/Log.php
Normal file
143
Aiko/Aiko/Libs/Log.php
Normal file
@ -0,0 +1,143 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
use Monolog\Logger;
|
||||
use Monolog\Handler\StreamHandler;
|
||||
|
||||
class Log
|
||||
{
|
||||
private static $env = null;
|
||||
private static $errorLog = null;
|
||||
private static $accessLog = null;
|
||||
private static $mobileAccessLog = null;
|
||||
private static $commitAttendance=null;
|
||||
public function __construct($env)
|
||||
{
|
||||
self::$env = $env;
|
||||
|
||||
|
||||
self::$errorLog = new Logger('errorLog');
|
||||
self::$errorLog->pushHandler(new StreamHandler(__SITE_PATH.'/log/Error-'.date('Y-m-d').'.log', Logger::ERROR));
|
||||
|
||||
self::$accessLog = new Logger('accessLog');
|
||||
self::$accessLog->pushHandler(new StreamHandler(__SITE_PATH.'/log/Access-'.date('Y-m-d').'.log', Logger::INFO));
|
||||
|
||||
self::$mobileAccessLog = new Logger('mobile_accessLog');
|
||||
self::$mobileAccessLog->pushHandler(new StreamHandler(__SITE_PATH.'/log/MobileAccess-'.date('Y-m-d').'.log', Logger::INFO));
|
||||
self::$commitAttendance = new Logger('commit_attendance');
|
||||
self::$commitAttendance->pushHandler(new StreamHandler(__SITE_PATH.'/log/commitAttendance-'.date('Y-m-d').'.log', Logger::INFO));
|
||||
|
||||
}
|
||||
|
||||
public function error($message, $data = array())
|
||||
{
|
||||
$data = $this->convertToArray($data);
|
||||
$ip = $this->getIp();
|
||||
$message = $ip.' '.$message;
|
||||
if (count($data) > 0) {
|
||||
self::$errorLog->addError($message, $data);
|
||||
} else {
|
||||
self::$errorLog->addError($message);
|
||||
}
|
||||
}
|
||||
|
||||
public function access($message, $data = array())
|
||||
{
|
||||
$data = $this->convertToArray($data);
|
||||
$ip = $this->getIp();
|
||||
$message = $ip.' '.$message;
|
||||
if (self::$env === '1') {
|
||||
if (count($data) > 0) {
|
||||
self::$accessLog->addInfo($message, $data);
|
||||
} else {
|
||||
self::$accessLog->addInfo($message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function customAccess($fileName,$message, $data = array())
|
||||
{
|
||||
|
||||
$ip = $this->getIp();
|
||||
$message = $ip.' '.$message;
|
||||
if (count($data) > 0) {
|
||||
$newLog= new Logger('custom-success-log');
|
||||
$newLog->pushHandler(new StreamHandler(__SITE_PATH.'/log/'.$fileName.'-'.date('Y-m-d').'.log', Logger::INFO));
|
||||
$data = $this->convertToArray($data);
|
||||
$newLog->addInfo($message, $data);
|
||||
} else {
|
||||
$newLog->addInfo($message);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public function customError($fileName,$message,$data=array())
|
||||
|
||||
{
|
||||
$newLog= new Logger('custom-error-log');
|
||||
$newLog->pushHandler(new StreamHandler(__SITE_PATH.'/log/'.$fileName.'-'.date('Y-m-d').'.log', Logger::ERROR));
|
||||
$data = $this->convertToArray($data);
|
||||
$ip = $this->getIp();
|
||||
$message = $ip.' '.$message;
|
||||
if (count($data) > 0) {
|
||||
$newLog->addError($message, $data);
|
||||
} else {
|
||||
$newLog->addError($message);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private function getIp()
|
||||
{
|
||||
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
|
||||
$ip = $_SERVER['HTTP_CLIENT_IP'];
|
||||
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
|
||||
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
|
||||
} else {
|
||||
$ip = $_SERVER['REMOTE_ADDR'];
|
||||
}
|
||||
|
||||
return $ip;
|
||||
}
|
||||
|
||||
private function convertToArray($data)
|
||||
{
|
||||
if (is_object($data)) {
|
||||
$jtext = json_encode($data);
|
||||
$arr = json_decode($jtext, true);
|
||||
|
||||
return $arr;
|
||||
} else {
|
||||
if (is_array($data)) {
|
||||
return $data;
|
||||
} else {
|
||||
return array();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function mobileAccess($message, $data = array())
|
||||
{
|
||||
$data = $this->convertToArray($data);
|
||||
$ip = $this->getIp();
|
||||
$message = $ip.' '.$message;
|
||||
if (count($data) > 0) {
|
||||
self::$mobileAccessLog->addInfo($message, $data);
|
||||
} else {
|
||||
self::$mobileAccessLog->addInfo($message);
|
||||
}
|
||||
}
|
||||
|
||||
public function commitAttendance($message, $data = array())
|
||||
{
|
||||
$data = $this->convertToArray($data);
|
||||
$ip = $this->getIp();
|
||||
$message = $ip.' '.$message;
|
||||
if (count($data) > 0) {
|
||||
self::$mobileAccessLog->addInfo($message, $data);
|
||||
} else {
|
||||
self::$mobileAccessLog->addInfo($message);
|
||||
}
|
||||
}
|
||||
}
|
3
Aiko/Aiko/Libs/Log.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/Log.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
85
Aiko/Aiko/Libs/LogAccess.php
Normal file
85
Aiko/Aiko/Libs/LogAccess.php
Normal file
@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
use \Aiko\Model;
|
||||
use \Aiko\Http;
|
||||
use PDOException;
|
||||
use PDO;
|
||||
class LogAccess extends Model {
|
||||
|
||||
|
||||
function __construct($registry) {
|
||||
parent::__construct($registry);
|
||||
}
|
||||
function saveLog($serviceName) {
|
||||
try {
|
||||
|
||||
$sql = 'insert into app_log(`service_name`,`username`) values(:service_name,:username)';
|
||||
|
||||
$stmt = $this->registry->db->prepare($sql);
|
||||
$stmt->bindValue(':service_name',$serviceName, PDO::PARAM_STR);
|
||||
$stmt->bindValue(':username',\Helper::getSessionVar('username'), PDO::PARAM_STR);
|
||||
$stmt->execute();
|
||||
return true;
|
||||
} catch (PDOException $e) {
|
||||
|
||||
$this->registry->log->error('Action : Insert data LogAcccess/saveLog :'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
|
||||
|
||||
return false;
|
||||
} catch (\ErrorException $e) {
|
||||
|
||||
$this->registry->log->error('Action : Insert data LogAcccess/saveLog :'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function viewLogByServiceName($serviceName)
|
||||
{
|
||||
try {
|
||||
|
||||
$sql = 'select `service_name`,`username`,`timestamp` from app_log where `service_name`=:service_name';
|
||||
|
||||
$stmt = $this->registry->db->prepare($sql);
|
||||
$stmt->bindValue(':service_name',$serviceName, PDO::PARAM_STR);
|
||||
$stmt->execute();
|
||||
$rs=$stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
|
||||
return $rs;
|
||||
} catch (PDOException $e) {
|
||||
$this->registry->log->error('LogAcccess/viewLogByServiceName :'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
|
||||
|
||||
return false;
|
||||
} catch (\ErrorException $e) {
|
||||
$this->registry->log->error('LogAcccess/viewLogByServiceName :'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function viewLogByUsername($username)
|
||||
{
|
||||
try {
|
||||
|
||||
$sql = 'select `service_name`,`username`,`timestamp` from app_log where `username`=:username';
|
||||
|
||||
$stmt = $this->registry->db->prepare($sql);
|
||||
$stmt->bindValue(':username',$username, PDO::PARAM_STR);
|
||||
$stmt->execute();
|
||||
$rs=$stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
|
||||
return $rs;
|
||||
} catch (PDOException $e) {
|
||||
$this->registry->log->error('LogAcccess/viewLogByServiceUsername :'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
|
||||
|
||||
return false;
|
||||
} catch (ErrorException $e) {
|
||||
$this->registry->log->error('LogAcccess/viewLogByServiceUsername :'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
3
Aiko/Aiko/Libs/LogAccess.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/LogAccess.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
36
Aiko/Aiko/Libs/Logdbtrait.php
Normal file
36
Aiko/Aiko/Libs/Logdbtrait.php
Normal file
@ -0,0 +1,36 @@
|
||||
<?php
|
||||
/**
|
||||
* trait berfungsi untuk log insert update dan delete
|
||||
*/
|
||||
namespace Aiko;
|
||||
use PDO;
|
||||
use PDOException;
|
||||
use ErrorException;
|
||||
trait Logdb
|
||||
{
|
||||
/**
|
||||
* summary
|
||||
*/
|
||||
public function insertLog($tableName,$data,$transactionType,$actionBy)
|
||||
{
|
||||
try {
|
||||
// print_r($tableName);
|
||||
// print_r($data);
|
||||
// print_r($transactionType);
|
||||
// print_r($actionBy);
|
||||
$sql = 'insert into log_transaction(`table_name`,`data`,`transaction_type`,`action_by`)values(
|
||||
:table_name,:data,:transaction_type,:action_by)';
|
||||
$stmt = $this->registry->db->prepare($sql);
|
||||
$stmt->bindValue(':table_name',$tableName, PDO::PARAM_STR);
|
||||
$stmt->bindValue(':data',$data,PDO::PARAM_STR);
|
||||
$stmt->bindValue(':transaction_type',$transactionType,PDO::PARAM_STR);
|
||||
$stmt->bindValue(':action_by',$actionBy,PDO::PARAM_STR);
|
||||
$stmt->execute();
|
||||
return true;
|
||||
} catch (PDOException $e) {
|
||||
return false;
|
||||
} catch (ErrorException $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
3
Aiko/Aiko/Libs/Logdbtrait.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/Logdbtrait.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
16
Aiko/Aiko/Libs/MyFpdi.php
Normal file
16
Aiko/Aiko/Libs/MyFpdi.php
Normal file
@ -0,0 +1,16 @@
|
||||
<?php
|
||||
namespace Aiko;
|
||||
use \fpdi\FPDI;
|
||||
|
||||
class MyFpdi extends FPDI
|
||||
{
|
||||
function Header()
|
||||
{
|
||||
// Fungsi Header kosong untuk menghilangkan header default
|
||||
}
|
||||
|
||||
function Footer()
|
||||
{
|
||||
// Fungsi Footer kosong untuk menghilangkan footer default
|
||||
}
|
||||
}
|
3
Aiko/Aiko/Libs/MyFpdi.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/MyFpdi.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
1302
Aiko/Aiko/Libs/MyPdf.php
Normal file
1302
Aiko/Aiko/Libs/MyPdf.php
Normal file
File diff suppressed because it is too large
Load Diff
3
Aiko/Aiko/Libs/MyPdf.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/MyPdf.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
35
Aiko/Aiko/Libs/Mycrypt.php
Normal file
35
Aiko/Aiko/Libs/Mycrypt.php
Normal file
@ -0,0 +1,35 @@
|
||||
<?php
|
||||
namespace Aiko;
|
||||
/**
|
||||
*
|
||||
*/
|
||||
class Mycrypt
|
||||
{
|
||||
private static $output = false;
|
||||
private static $encrypt_method = __ENCRYPT_METHOD;
|
||||
private static $secret_key = __SECRET_KEY;
|
||||
private static $secret_iv = __SECRET_IV;
|
||||
|
||||
private function __construct(){}
|
||||
|
||||
public static function encrypt($string)
|
||||
{
|
||||
$key = hash('sha256', self::$secret_key);
|
||||
$iv = substr(hash('sha256', self::$secret_iv), 0, 16);
|
||||
self::$output = openssl_encrypt($string, self::$encrypt_method, $key, 0, $iv);
|
||||
return base64_encode(self::$output);
|
||||
}
|
||||
|
||||
public static function decrypt($string)
|
||||
{
|
||||
$key = hash('sha256', self::$secret_key);
|
||||
$iv = substr(hash('sha256', self::$secret_iv), 0, 16);
|
||||
return openssl_decrypt(base64_decode($string), self::$encrypt_method, $key, 0, $iv);
|
||||
}
|
||||
|
||||
private function __destruct(){}
|
||||
}
|
||||
|
||||
|
||||
|
||||
?>
|
3
Aiko/Aiko/Libs/Mycrypt.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/Mycrypt.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
35
Aiko/Aiko/Libs/Query.php
Normal file
35
Aiko/Aiko/Libs/Query.php
Normal file
@ -0,0 +1,35 @@
|
||||
<?php
|
||||
namespace Aiko\Database;
|
||||
class query
|
||||
{
|
||||
private $param;
|
||||
private $debug_mode;
|
||||
private $registry;
|
||||
private $query;
|
||||
public function __construct($registry,$query,$debug_mode) {
|
||||
$this->debug_mode=$debug_mode;
|
||||
$this->query=$query;
|
||||
$this->registry=$registry;
|
||||
}
|
||||
public function getData($param=array())
|
||||
{
|
||||
try{
|
||||
|
||||
} catch (PDOException $e)
|
||||
{
|
||||
if($this->debug_mode)
|
||||
{
|
||||
return $e->getMessage();
|
||||
}else
|
||||
{
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
$this->param=$param;
|
||||
$obj = new processdata();
|
||||
return $obj;
|
||||
}
|
||||
}
|
3
Aiko/Aiko/Libs/Query.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/Query.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
41
Aiko/Aiko/Libs/QueryParam.php
Normal file
41
Aiko/Aiko/Libs/QueryParam.php
Normal file
@ -0,0 +1,41 @@
|
||||
<?php
|
||||
namespace Aiko\Database;
|
||||
class QueryParam
|
||||
{
|
||||
private $dataType;
|
||||
private $data;
|
||||
private $placeHolder;
|
||||
private $query;
|
||||
public function dataType($dataType)
|
||||
{
|
||||
$this->dataType=$dataType;
|
||||
return $this;
|
||||
}
|
||||
public function query($query)
|
||||
{
|
||||
$this->query=$query;
|
||||
return $this;
|
||||
}
|
||||
public function data($data)
|
||||
{
|
||||
$this->data=$data;
|
||||
return $this;
|
||||
}
|
||||
public function placeHolder($placeHolder)
|
||||
{
|
||||
$this->placeHolder=$placeHolder;
|
||||
return $this;
|
||||
}
|
||||
public function getDataType()
|
||||
{
|
||||
return $this->dataType;
|
||||
}
|
||||
public function getData()
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
public function getPlaceHolder()
|
||||
{
|
||||
return $this->placeHolder;
|
||||
}
|
||||
}
|
3
Aiko/Aiko/Libs/QueryParam.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/QueryParam.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
24
Aiko/Aiko/Libs/QueryProcess.php
Normal file
24
Aiko/Aiko/Libs/QueryProcess.php
Normal file
@ -0,0 +1,24 @@
|
||||
<?php
|
||||
namespace Aiko\Database;
|
||||
class QueryProcess{
|
||||
public function getJson()
|
||||
{
|
||||
|
||||
}
|
||||
public function getAssoc()
|
||||
{
|
||||
|
||||
}
|
||||
public function getObject()
|
||||
{
|
||||
|
||||
}
|
||||
public function getColumn($column)
|
||||
{
|
||||
|
||||
}
|
||||
public function getField($field)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
3
Aiko/Aiko/Libs/QueryProcess.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/QueryProcess.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
176
Aiko/Aiko/Libs/Session.php
Normal file
176
Aiko/Aiko/Libs/Session.php
Normal file
@ -0,0 +1,176 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
use \Aiko\Model;
|
||||
use \Aiko\Http;
|
||||
use \SessionHandlerInterface;
|
||||
use PDOException;
|
||||
use PDO;
|
||||
class Session extends Model implements SessionHandlerInterface {
|
||||
// session-lifetime
|
||||
var $lifeTime;
|
||||
// mysql-handle
|
||||
var $dbHandle;
|
||||
|
||||
function __construct($registry) {
|
||||
parent::__construct($registry);
|
||||
}
|
||||
function open($savePath, $sessName) {
|
||||
// get session-lifetime
|
||||
$this->lifeTime = get_cfg_var("session.gc_maxlifetime");
|
||||
// open database-connection
|
||||
return true;
|
||||
}
|
||||
function close() {
|
||||
$this->gc(ini_get('session.gc_maxlifetime'));
|
||||
|
||||
}
|
||||
function read($sessID) {
|
||||
// fetch session-data
|
||||
try {
|
||||
$this->registry->log->error('read :'.$sessID.' :');
|
||||
// var_dump($sessID);
|
||||
$query="SELECT session_data AS d FROM ws_sessions WHERE session_id = '$sessID' AND session_expires > ".time();
|
||||
$stmt=$this->registry->db->prepare($query);
|
||||
$stmt->execute();
|
||||
$rs=$stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
return (count($rs)>0)?$rs[0]['d']:'';
|
||||
} catch (PDOException $e) {
|
||||
|
||||
$this->registry->log->error('module session/read :'.$e->getMessage());
|
||||
return '';
|
||||
}
|
||||
}
|
||||
function write($sessID,$sessData) {
|
||||
// new session-expire-time
|
||||
|
||||
$this->registry->log->error('write :'.$sessID.' :'.$sessData);
|
||||
$newExp = time() + $this->lifeTime;
|
||||
// is a session with this id in the database?
|
||||
$fd=0;
|
||||
try {
|
||||
$sql="SELECT count(0) as found FROM ws_sessions
|
||||
WHERE session_id =:sessionID";
|
||||
$stmt=$this->registry->db->prepare($sql);
|
||||
$stmt->bindValue(':sessionID',$sessID,PDO::PARAM_STR);
|
||||
$stmt->execute();
|
||||
$rs=$stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
$fd=$rs[0]['found'];
|
||||
} catch (PDOException $e) {
|
||||
$fd=0;
|
||||
$this->registry->log->error('module session /write :'.$e->getMessage());
|
||||
}
|
||||
|
||||
|
||||
if($fd>0)
|
||||
{
|
||||
if(!empty($sessData)){
|
||||
try {
|
||||
$sql="UPDATE ws_sessions
|
||||
SET session_expires =:sessionExpired,
|
||||
session_data =:sessionData
|
||||
WHERE session_id =:sessionID";
|
||||
|
||||
$stmt=$this->registry->db->prepare($sql);
|
||||
$stmt->bindValue(':sessionID',$sessID,PDO::PARAM_STR);
|
||||
$stmt->bindValue(':sessionExpired',$newExp,PDO::PARAM_INT);
|
||||
$stmt->bindValue(':sessionData',$sessData,PDO::PARAM_STR);
|
||||
$stmt->execute();
|
||||
$resUpdate=true;
|
||||
} catch (PDOException $e) {
|
||||
$this->registry->log->error('module session /write :'.$e->getMessage());
|
||||
$resUpdate=false;
|
||||
}
|
||||
return $resUpdate;
|
||||
}else
|
||||
{
|
||||
try {
|
||||
$sql="delete from ws_sessions WHERE session_id =:sessionID";
|
||||
$stmt=$this->registry->db->prepare($sql);
|
||||
$stmt->bindValue(':sessionID',$sessID,PDO::PARAM_STR);
|
||||
$stmt->execute();
|
||||
$resultDelete=true;
|
||||
} catch (PDOException $e) {
|
||||
$this->registry->log->error('module session /write :'.$e->getMessage());
|
||||
$resultDelete=false;
|
||||
}
|
||||
|
||||
return $resultDelete;
|
||||
}
|
||||
}else
|
||||
{
|
||||
$resultInsert=false;
|
||||
|
||||
if(!empty($sessData)){
|
||||
try {
|
||||
$sql="INSERT INTO ws_sessions (
|
||||
session_id,
|
||||
session_expires,
|
||||
session_data)
|
||||
VALUES(
|
||||
:sessionID,
|
||||
:sessionExpired,
|
||||
:sessionData)";
|
||||
$stmt=$this->registry->db->prepare($sql);
|
||||
$stmt->bindValue(':sessionID',$sessID,PDO::PARAM_STR);
|
||||
$stmt->bindValue(':sessionExpired',$newExp,PDO::PARAM_INT);
|
||||
$stmt->bindValue(':sessionData',$sessData,PDO::PARAM_STR);
|
||||
$stmt->execute();
|
||||
$resultInsert=true;
|
||||
} catch (PDOException $e) {
|
||||
$this->registry->log->error('module session /write :'.$e->getMessage());
|
||||
$resultInsert=false;
|
||||
}
|
||||
|
||||
}
|
||||
return $resultInsert;
|
||||
}
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
function destroy($sessID) {
|
||||
|
||||
try {
|
||||
|
||||
$sql="DELETE FROM ws_sessions WHERE session_id = '$sessID'";
|
||||
$stmt=$this->registry->db->prepare($sql);
|
||||
$stmt->execute();
|
||||
|
||||
return true;
|
||||
} catch (PDOException $exc) {
|
||||
$this->registry->log->error('module session /write :'.$e->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function gc($sessMaxLifeTime) {
|
||||
|
||||
|
||||
try{
|
||||
|
||||
|
||||
/**
|
||||
* sql dibawah ini digunakan untuk ambil session id yang sudah expired dan update data user session nya jika menggunakan sesion user
|
||||
*/
|
||||
$sql="select session_id from ws_sessions WHERE session_expires < ".time();
|
||||
$stmt=$this->registry->db->prepare($sql);
|
||||
$stmt->execute();
|
||||
$rs=$stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
|
||||
$sql="DELETE FROM ws_sessions WHERE session_expires < ".time();
|
||||
$stmt=$this->registry->db->prepare($sql);
|
||||
$stmt->execute();
|
||||
return true;
|
||||
} catch (PDOException $e)
|
||||
{
|
||||
$this->registry->log->error('module session /write :'.$e->getMessage());
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
?>
|
3
Aiko/Aiko/Libs/Session.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/Session.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
134
Aiko/Aiko/Libs/Storage.php
Normal file
134
Aiko/Aiko/Libs/Storage.php
Normal file
@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
use ErrorException;
|
||||
use Exception;
|
||||
use Helper;
|
||||
use Symfony\Component\HttpFoundation\File\Exception\FileException;
|
||||
use Symfony\Component\HttpFoundation\File\UploadedFile;
|
||||
|
||||
class Storage
|
||||
{
|
||||
private $isProduction;
|
||||
private $registry;
|
||||
private $baseStorage;
|
||||
|
||||
public function __construct($registry)
|
||||
{
|
||||
$this->registry = $registry;
|
||||
$this->isProduction = $this->registry->config->environment === 'production';
|
||||
$this->baseStorage = $this->isProduction ? $this->registry->config->base_storage : __SITE_PATH . '/hcportal_docs/';
|
||||
}
|
||||
|
||||
public function fromException($e, $action)
|
||||
{
|
||||
return Helper::handleException($this->registry, $e, "storage", $action, false, "Storage");
|
||||
}
|
||||
|
||||
/** @param UploadedFile $file */
|
||||
public function validateFile($file, $maxSize = 2048, $allowedMime = [])
|
||||
{
|
||||
if ($file instanceof UploadedFile) {
|
||||
$mime = $file->getMimeType();
|
||||
if (in_array($mime, $allowedMime)) return true;
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
//
|
||||
//
|
||||
// @param $options = [
|
||||
// 'mime' => [],
|
||||
// 'size' => 0
|
||||
// ]
|
||||
public function store($file, $folderName = 'temp', $prefix = '', $options = [])
|
||||
{
|
||||
try {
|
||||
$storage = $this->trimSlashes($this->baseStorage . '/' . $folderName . '/');
|
||||
$default = $this->generateFilename($file);
|
||||
$filename = $default;
|
||||
if ($prefix) {
|
||||
$filename = $prefix . '_' . $default;
|
||||
}
|
||||
$file->move($storage, $filename);
|
||||
return $filename;
|
||||
} catch (FileException $e) {
|
||||
return $this->fromException($e, "store");
|
||||
} catch (ErrorException $e) {
|
||||
return $this->fromException($e, "store");
|
||||
}
|
||||
}
|
||||
|
||||
public function delete($filename, $folderName = 'temp')
|
||||
{
|
||||
try {
|
||||
$link = $this->trimSlashes($this->baseStorage . '/' . $folderName . '/' . $filename);
|
||||
if (file_exists($link)) {
|
||||
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
|
||||
$fileTmp = $link;
|
||||
$fileTmp = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR, $fileTmp);
|
||||
@unlink($fileTmp);
|
||||
} else {
|
||||
unlink($link);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (Exception $e) {
|
||||
return $this->fromException($e, "delete");
|
||||
}
|
||||
}
|
||||
|
||||
public function url($filename, $path = 'temp', $isLocal = false)
|
||||
{
|
||||
if (!$filename) {
|
||||
return null;
|
||||
}
|
||||
$filePath = $this->trimSlashes('hcportal_docs/' . $path . '/' . $filename);
|
||||
$prefix = $this->registry->config->server_address;
|
||||
if($isLocal){
|
||||
$prefix = __SITE_PATH.'/';
|
||||
}
|
||||
return $prefix . $filePath;
|
||||
}
|
||||
|
||||
public function generateFilename($file)
|
||||
{
|
||||
$time = time();
|
||||
$filename = uniqid() . '_' . $time . '.' . $file->guessExtension();
|
||||
return $filename;
|
||||
}
|
||||
|
||||
public function isValidImage($mimeType)
|
||||
{
|
||||
return $this->validateMime($mimeType, [
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/jpg'
|
||||
]);
|
||||
return true;
|
||||
}
|
||||
|
||||
public function isValidDocument($mimeType)
|
||||
{
|
||||
return $this->validateMime($mimeType, [
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'application/vnd.ms-excel',
|
||||
'application/pdf'
|
||||
]);
|
||||
}
|
||||
|
||||
private function validateMime($mimeType, $mimeClientAlowed)
|
||||
{
|
||||
if (!in_array($mimeType, $mimeClientAlowed)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private function trimSlashes($str)
|
||||
{
|
||||
return preg_replace('/(\/+)/', '/', $str);
|
||||
}
|
||||
}
|
3
Aiko/Aiko/Libs/Storage.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/Storage.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
349
Aiko/Aiko/Libs/Token.php
Normal file
349
Aiko/Aiko/Libs/Token.php
Normal file
@ -0,0 +1,349 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
use Aiko\Log;
|
||||
use Firebase\JWT\JWT;
|
||||
|
||||
class Token
|
||||
{
|
||||
|
||||
public function get_token($area = 'default')
|
||||
{
|
||||
$token = hash('sha512', mt_rand(0, mt_getrandmax()) . microtime(true));
|
||||
$_SESSION['token'] = $token;
|
||||
|
||||
return $token;
|
||||
}
|
||||
public function check_token($token, $area = 'default')
|
||||
{
|
||||
// var_dump($_SESSION);
|
||||
$sessiontoken = $this->get_token_from_session('token');
|
||||
// var_dump($sessiontoken);
|
||||
// exit();
|
||||
|
||||
|
||||
$valid = strlen($sessiontoken) == 128 && strlen($token) == 128 && $sessiontoken == $token;
|
||||
|
||||
$this->get_token($area); // refresh token
|
||||
|
||||
return $valid;
|
||||
}
|
||||
public function get_token_from_url()
|
||||
{
|
||||
$token = isset($_GET['token']) ? $_GET['token'] : '';
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
public function get_token_from_session($key)
|
||||
{
|
||||
$token = isset($_SESSION[$key]) ? $_SESSION[$key] : '';
|
||||
|
||||
return $token;
|
||||
}
|
||||
public function getTokenAuthUser()
|
||||
{
|
||||
$token = hash('sha512', mt_rand(0, mt_getrandmax()) . microtime(true));
|
||||
$_SESSION['tokenAuth'] = $token;
|
||||
|
||||
return $token;
|
||||
}
|
||||
public function check_tokenAuthUser($token)
|
||||
{
|
||||
$sessiontoken = $this->get_token_from_session('tokenAuth');
|
||||
$valid = strlen($sessiontoken) == 128 && strlen($token) == 128 && $sessiontoken == $token;
|
||||
if ($valid) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function set_cookie()
|
||||
{
|
||||
$result = password_hash('4pl1k4s1D1sd1K', PASSWORD_DEFAULT, array('cost' => 10));
|
||||
// $res = setcookie('XSRF-TOKEN', $result, time() + 86400, $_SERVER['REQUEST_URI'],'',false,false);
|
||||
|
||||
$res = setcookie('XSRF-TOKEN', $result, time() + 86400, '/');
|
||||
if ($res) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public function cek_cookie($clientCookie)
|
||||
{
|
||||
$result = false;
|
||||
if (isset($_COOKIE['XSRF-TOKEN'])) {
|
||||
$serverCookie = $_COOKIE['XSRF-TOKEN'];
|
||||
$result = $this->cek_hash($clientCookie, $serverCookie);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function cek_hash($clientCookie, $serverCookie)
|
||||
{
|
||||
if ($clientCookie == $serverCookie) {
|
||||
return $this->set_cookie();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static function wrapToken($jwt, $chipper)
|
||||
{
|
||||
try {
|
||||
if (strlen($chipper) <> 6) {
|
||||
throw new \ErrorException('chipper failed');
|
||||
}
|
||||
$headerPreffix = (int) substr($chipper, 0, 1);
|
||||
$headerSuffix = (int) substr($chipper, 1, 1);
|
||||
$payloadPreffix = (int) substr($chipper, 2, 1);
|
||||
$payloadSuffix = (int) substr($chipper, 3, 1);
|
||||
$signPreffix = (int) substr($chipper, 4, 1);
|
||||
$signSuffix = (int) substr($chipper, 5, 1);
|
||||
|
||||
$jwtPart = explode('.', $jwt);
|
||||
|
||||
$newJwt = self::randomChars($headerPreffix) . $jwtPart[0] . self::randomChars($headerSuffix);
|
||||
|
||||
$newJwt .= '.' . self::randomChars($payloadPreffix) . $jwtPart[1] . self::randomChars($payloadSuffix);
|
||||
|
||||
$newJwt .= '.' . self::randomChars($signPreffix) . $jwtPart[2] . self::randomChars($signSuffix);
|
||||
|
||||
return $newJwt;
|
||||
} catch (\Exception $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static function unWrapToken($jwt, $chipper)
|
||||
{
|
||||
try {
|
||||
if (strlen($chipper) <> 6) {
|
||||
throw new \ErrorException('chipper failed');
|
||||
}
|
||||
|
||||
$headerPreffix = (int) substr($chipper, 0, 1);
|
||||
$headerSuffix = (int) substr($chipper, 1, 1);
|
||||
$payloadPreffix = (int) substr($chipper, 2, 1);
|
||||
$payloadSuffix = (int) substr($chipper, 3, 1);
|
||||
$signPreffix = (int) substr($chipper, 4, 1);
|
||||
$signSuffix = (int) substr($chipper, 5, 1);
|
||||
|
||||
$jwtPart = explode('.', $jwt);
|
||||
|
||||
$newString = self::removePreSuf($jwtPart[0], $headerPreffix, $headerSuffix);
|
||||
if ($newString == false) {
|
||||
throw new \ErrorException('failed clean wrapper header');
|
||||
}
|
||||
$header = $newString;
|
||||
|
||||
$newString = self::removePreSuf($jwtPart[1], $payloadPreffix, $payloadSuffix);
|
||||
if ($newString == false) {
|
||||
throw new \ErrorException('failed clean wrapper payload');
|
||||
}
|
||||
$payload = $newString;
|
||||
|
||||
$newString = self::removePreSuf($jwtPart[2], $signPreffix, $signSuffix);
|
||||
if ($newString == false) {
|
||||
throw new \ErrorException('failed clean wrapper sign');
|
||||
}
|
||||
$sign = $newString;
|
||||
|
||||
return $header . '.' . $payload . '.' . $sign;
|
||||
} catch (\ErrorException $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static function removePreSuf($string, $preffix, $suffix)
|
||||
{
|
||||
$jum = strlen(trim($string));
|
||||
$totWrapper = ($preffix + $suffix);
|
||||
$tot = $totWrapper + 10; // set minimum text
|
||||
if ($jum > $tot) {
|
||||
$total = $jum - $totWrapper;
|
||||
$newString = substr($string, $preffix, $total);
|
||||
return $newString;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function randomChars($numChars)
|
||||
{
|
||||
$str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuzwxyz';
|
||||
return substr(str_shuffle($str), 0, $numChars);
|
||||
}
|
||||
|
||||
public static function encodeJWT($serverName, $dataUser, $chipper = '000000')
|
||||
{
|
||||
|
||||
try {
|
||||
|
||||
$log = new Log('1');
|
||||
// $publicKey = file_get_contents('/Users/suhendra/mykey/suhendra_rsa.pub');
|
||||
|
||||
$privateKey = file_get_contents(__SITE_PATH . '/mykey/hcportalprivate.pem');
|
||||
|
||||
// $privateKey = openssl_get_privatekey('file:///Users/suhendra/mykey/suhendra_rsa','suh3ndr4');
|
||||
// var_dump($privateKey);
|
||||
|
||||
//$tokenId = base64_encode(\mcrypt_create_iv(32));
|
||||
$tokenId = base64_encode(\openssl_random_pseudo_bytes(64));
|
||||
// $random = mt_rand(0, 999999);
|
||||
// $random_string = sha1($random);
|
||||
//$tokenId = base64_encode(date('Y-m-d H:i:s'));
|
||||
$issuedAt = time();
|
||||
$notBefore = time();
|
||||
$expire = $notBefore + __LIFETIMEJWT; // Adding 10 menit
|
||||
|
||||
/*
|
||||
* Create the token as an array
|
||||
*/
|
||||
$data = [
|
||||
'iat' => $issuedAt, // Issued at: time when the token was generated
|
||||
'jti' => $tokenId, // Json Token Id: an unique identifier for the token / A unique string, could be used to validate a token, but goes against not having a centralized issuer authority.
|
||||
'iss' => $serverName, // A string containing the name or identifier of the issuer application. Can be a domain name and can be used to discard tokens from other applications.
|
||||
'nbf' => $notBefore, // Timestamp of when the token should start being considered valid. Should be equal to or greater than iat. In this case, the token will begin to be valid 10 seconds
|
||||
'exp' => $expire, // Timestamp of when the token should cease to be valid. Should be greater than iat and nbf. In this case, the token will expire 60 seconds after being issued.
|
||||
'data' => $dataUser,
|
||||
];
|
||||
|
||||
$jwt = JWT::encode(
|
||||
$data, //Data to be encoded in the JWT
|
||||
$privateKey, // The signing key
|
||||
'RS256' // Algorithm used to sign the token, see https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40#section-3
|
||||
);
|
||||
|
||||
// var_dump($jwt);
|
||||
|
||||
$newJwt = self::wrapToken($jwt, $chipper);
|
||||
// var_dump($newJwt);
|
||||
|
||||
if ($newJwt == false) {
|
||||
throw new \ErrorException('Failed wrap Token');
|
||||
}
|
||||
|
||||
$dataUser['expired'] = $expire;
|
||||
$dataHeader = array(
|
||||
'jwt' => $newJwt,
|
||||
'tokenID' => $tokenId,
|
||||
'appID' => $serverName,
|
||||
'data' => $dataUser,
|
||||
'expired' => $expire
|
||||
);
|
||||
|
||||
return $dataHeader;
|
||||
} catch (\ErrorException $e) {
|
||||
$log->error('encode token token/decodeJWT' . $e->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static function decodeJWT($jwt, $chipper = '000000')
|
||||
{
|
||||
try {
|
||||
$log = new Log('1');
|
||||
|
||||
$publicKey = file_get_contents(__SITE_PATH . '/mykey/hcportalpublic.pem');
|
||||
|
||||
$newJwt = self::unWrapToken($jwt, $chipper);
|
||||
|
||||
$token = JWT::decode($newJwt, $publicKey, array('RS256'));
|
||||
|
||||
return $token;
|
||||
} catch (\DomainException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\UnexpectedValueException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\DateTime $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\SignatureInvalidException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\BeforeValidException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\Firebase\JWT\ExpiredException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static function decodeJWTNew($jwt, $chipper = '000000')
|
||||
{
|
||||
try {
|
||||
$log = new Log('1');
|
||||
|
||||
$publicKey = file_get_contents(__SITE_PATH . '/mykey/hcportalpublic.pem');
|
||||
|
||||
$newJwt = self::unWrapToken($jwt, $chipper);
|
||||
|
||||
$token = JWT::decode($newJwt, $publicKey, array('RS256'));
|
||||
return $token;
|
||||
} catch (\DomainException $e) {
|
||||
$log->error('decode token token/decodeJWT 2 ' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return 2;
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
$log->error('decode token token/decodeJWT 3' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return 3;
|
||||
} catch (\UnexpectedValueException $e) {
|
||||
$log->error('decode token token/decodeJWT 4' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
if ($e->getMessage() == 'Expired token') {
|
||||
return 8;
|
||||
}
|
||||
return 4;
|
||||
} catch (\DateTime $e) {
|
||||
$log->error('decode token token/decodeJWT 5' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return 5;
|
||||
} catch (\SignatureInvalidException $e) {
|
||||
$log->error('decode token token/decodeJWT 6' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return 6;
|
||||
} catch (\BeforeValidException $e) {
|
||||
$log->error('decode token token/decodeJWT 7' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return 7;
|
||||
} catch (\Firebase\JWT\ExpiredException $e) {
|
||||
$log->error('decode token token/decodeJWT 8' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return 8;
|
||||
}
|
||||
}
|
||||
|
||||
public static function decodePlainJWT($jwt, $key = null)
|
||||
{
|
||||
try {
|
||||
$log = new Log('1');
|
||||
|
||||
$token = JWT::decode($jwt, $key, array('HS256'));
|
||||
|
||||
return $token;
|
||||
} catch (\DomainException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\UnexpectedValueException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\Firebase\JWT\SignatureInvalidException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\Firebase\JWT\BeforeValidException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
} catch (\Firebase\JWT\ExpiredException $e) {
|
||||
$log->error('decode token token/decodeJWT' . $e->getMessage() . 'JWT |' . $jwt);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
3
Aiko/Aiko/Libs/Token.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/Token.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
87
Aiko/Aiko/Libs/TokenSanitation.php
Normal file
87
Aiko/Aiko/Libs/TokenSanitation.php
Normal file
@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
class TokenSanitation
|
||||
{
|
||||
private $token='';
|
||||
private $errors=array();
|
||||
public function __construct($jwt)
|
||||
{
|
||||
// harus di set per client
|
||||
$clientChipper='542346';
|
||||
$this->token=$this->unWrapToken($jwt,$clientChipper);
|
||||
}
|
||||
|
||||
public function getToken(){
|
||||
return $this->token;
|
||||
}
|
||||
|
||||
public function getErros(){
|
||||
return $this->errors;
|
||||
}
|
||||
|
||||
private function unWrapToken($jwt, $chipper)
|
||||
{
|
||||
try {
|
||||
if (strlen($chipper) <> 6) {
|
||||
throw new \ErrorException('chipper failed');
|
||||
}
|
||||
|
||||
$headerPreffix = (int) substr($chipper, 0, 1);
|
||||
$headerSuffix = (int) substr($chipper, 1, 1);
|
||||
$payloadPreffix = (int) substr($chipper, 2, 1);
|
||||
$payloadSuffix = (int) substr($chipper, 3, 1);
|
||||
$signPreffix = (int) substr($chipper, 4, 1);
|
||||
$signSuffix = (int) substr($chipper, 5, 1);
|
||||
|
||||
$jwtPart = explode('.', $jwt);
|
||||
|
||||
|
||||
|
||||
if (count($jwtPart) != 4) {
|
||||
throw new \ErrorException('token part invalid');
|
||||
}
|
||||
|
||||
|
||||
$newString = $this->removePreSuf($jwtPart[0], $headerPreffix, $headerSuffix);
|
||||
if ($newString == false) {
|
||||
throw new \ErrorException('failed clean wrapper header');
|
||||
}
|
||||
$header = $newString;
|
||||
|
||||
$newString = $this->removePreSuf($jwtPart[1], $payloadPreffix, $payloadSuffix);
|
||||
if ($newString == false) {
|
||||
throw new \ErrorException('failed clean wrapper payload');
|
||||
}
|
||||
$payload = $newString;
|
||||
|
||||
$newString = $this->removePreSuf($jwtPart[2], $signPreffix, $signSuffix);
|
||||
if ($newString == false) {
|
||||
throw new \ErrorException('failed clean wrapper sign');
|
||||
}
|
||||
$sign = $newString;
|
||||
|
||||
return $header . '.' . $payload . '.' . $sign;
|
||||
} catch (\ErrorException $e) {
|
||||
array_push($this->errors,array($e->getMessage()));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private function removePreSuf($string, $preffix, $suffix)
|
||||
{
|
||||
$jum = strlen(trim($string));
|
||||
$totWrapper = ($preffix + $suffix);
|
||||
$tot = $totWrapper + 10; // set minimum text
|
||||
if ($jum > $tot) {
|
||||
$total = $jum - $totWrapper;
|
||||
$newString = substr($string, $preffix, $total);
|
||||
return $newString;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
}
|
3
Aiko/Aiko/Libs/TokenSanitation.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/TokenSanitation.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
50
Aiko/Aiko/Libs/Trait.php
Normal file
50
Aiko/Aiko/Libs/Trait.php
Normal file
@ -0,0 +1,50 @@
|
||||
<?php
|
||||
namespace Aiko;
|
||||
|
||||
/**
|
||||
* Main Trait
|
||||
*/
|
||||
trait Maintrait
|
||||
{
|
||||
/**
|
||||
* asumsi data yang di kirim sudah ada tidak perlu cek lagi dan array harus 2 dimensi
|
||||
*/
|
||||
public function saveToTmpTable($registry,$list,$fields,$tblname='main_tmp_table')
|
||||
{
|
||||
try {
|
||||
$registry->db->beginTransaction();
|
||||
|
||||
// drop tmp table
|
||||
$sqlDropExist = "DROP TEMPORARY TABLE IF EXISTS $tblname";
|
||||
$stmtDropExist=$this->registry->db->prepare($sqlDropExist);
|
||||
$stmtDropExist->execute();
|
||||
|
||||
// create table
|
||||
$sqlCreate='CREATE TEMPORARY TABLE '.$tblname. ' ( ';
|
||||
$sqlCreate .=$fields[0]['field'].' '.$fields[0]['type'].'('.$fields[0]['length'].')';
|
||||
$jum=count($fields);
|
||||
for ($i = 1; $i < $jum; $i++) {
|
||||
$sqlCreate .=' , '.$fields[$i]['field'].' '.$fields[$i]['type'].'('.$fields[$i]['length'].')';
|
||||
}
|
||||
|
||||
|
||||
$sqlCreate .=')';
|
||||
|
||||
var_dump($sqlCreate);
|
||||
|
||||
$registry->db->commit();
|
||||
|
||||
return true;
|
||||
} catch (PDOException $e) {
|
||||
$registry->db->rollBack();
|
||||
$this->registry->log->error('Main trait in lib /saveToTmpTable :'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
|
||||
|
||||
return false;
|
||||
} catch (ErrorException $e) {
|
||||
$registry->db->rollBack();
|
||||
$this->registry->log->error('Main trait in lib /saveToTmpTable :'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
3
Aiko/Aiko/Libs/Trait.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/Trait.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
110
Aiko/Aiko/Libs/Validator.php
Normal file
110
Aiko/Aiko/Libs/Validator.php
Normal file
@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
use Exception;
|
||||
|
||||
class Validator
|
||||
{
|
||||
|
||||
private $request = [];
|
||||
private $rules = [];
|
||||
private $errorBag = [];
|
||||
public $valid = [];
|
||||
|
||||
public function __construct($request, $rules = [])
|
||||
{
|
||||
$this->rules = $rules;
|
||||
if (!is_array($request) && is_object($request)) {
|
||||
$this->request = json_decode(json_encode($request), true);
|
||||
} else {
|
||||
$this->request = $request;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $paramKey
|
||||
* @param \Closure($value, $params): string|null $validatorFn
|
||||
*/
|
||||
public function addRule($paramKey, $validatorFn, $messages = [])
|
||||
{
|
||||
array_push($this->rules, new ValidationRule($this->request, $paramKey, $validatorFn, $messages));
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function fails()
|
||||
{
|
||||
return count($this->errorBag) > 0;
|
||||
}
|
||||
|
||||
public function safe($key = null)
|
||||
{
|
||||
if (is_null($key)) {
|
||||
return $this->valid;
|
||||
}
|
||||
if (isset($this->valid[$key])) {
|
||||
return $this->valid[$key];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public function all()
|
||||
{
|
||||
return $this->request;
|
||||
}
|
||||
|
||||
public function only($keys = [])
|
||||
{
|
||||
$request = [];
|
||||
foreach ($keys as $key) {
|
||||
if (array_key_exists($key, $this->request)) {
|
||||
$request[$key] = $this->request[$key];
|
||||
}
|
||||
}
|
||||
return $request;
|
||||
}
|
||||
|
||||
public function errors()
|
||||
{
|
||||
return $this->errorBag;
|
||||
}
|
||||
|
||||
public function validate($throw = false)
|
||||
{
|
||||
/** @var ValidationRule $rule */
|
||||
foreach ($this->rules as $rule) {
|
||||
if (!$rule->validate()) {
|
||||
if ($throw) {
|
||||
throw new ValidatorException($rule->key, $rule->errorBag);
|
||||
}
|
||||
array_push($this->errorBag, $rule->errorBag);
|
||||
continue;
|
||||
}
|
||||
$this->valid[$rule->key] = $rule->getParamValue();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class ValidatorException extends Exception
|
||||
{
|
||||
private $data;
|
||||
|
||||
// Redefine the exception so message isn't optional
|
||||
public function __construct($message, $data = [], $previous = null)
|
||||
{
|
||||
parent::__construct($message, 0, $previous);
|
||||
$this->data = $data;
|
||||
}
|
||||
|
||||
// custom string representation of object
|
||||
public function __toString()
|
||||
{
|
||||
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
|
||||
}
|
||||
|
||||
public function getData()
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
}
|
3
Aiko/Aiko/Libs/Validator.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/Validator.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
101
Aiko/Aiko/Libs/ValidatorRule.php
Normal file
101
Aiko/Aiko/Libs/ValidatorRule.php
Normal file
@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
use ReflectionClass;
|
||||
|
||||
class ValidationRule
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public $key;
|
||||
|
||||
/**
|
||||
* @var \Closure|string
|
||||
*/
|
||||
public $action;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
public $paramBag = [];
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
public $errorBag = [];
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
public $messages = [];
|
||||
|
||||
public function __construct($paramBag, $key, $action, $messages = [])
|
||||
{
|
||||
$this->key = $key;
|
||||
$this->action = $action;
|
||||
$this->paramBag = $paramBag;
|
||||
$this->messages = $messages;
|
||||
}
|
||||
|
||||
public function validate()
|
||||
{
|
||||
$param = $this->getParamValue();
|
||||
if (is_callable($this->action)) {
|
||||
$fn = $this->action;
|
||||
$message = $fn($param, $this->paramBag);
|
||||
if ($message !== null) {
|
||||
$this->addError($message);
|
||||
return false;
|
||||
}
|
||||
} else if (is_string($this->action)) {
|
||||
$repo = new ValidatorRuleCollection();
|
||||
$ref = new ReflectionClass($repo);
|
||||
$method = $this->action;
|
||||
if (strpos($this->action, '|') != false) {
|
||||
$exp = explode('|', $this->action);
|
||||
$method = $exp[0];
|
||||
}
|
||||
try {
|
||||
$refMethod = $ref->getMethod($method);
|
||||
$result = $refMethod->invokeArgs(new ValidatorRuleCollection(), [$this->key, $this->action, $param, $this->paramBag]);
|
||||
if (!is_null($result)) {
|
||||
$this->addError($result);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (\ReflectionException $e) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// defensive action
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public function parseMessage($messageKey)
|
||||
{
|
||||
if (array_key_exists($messageKey, $this->messages)) {
|
||||
return $this->messages[$messageKey];
|
||||
}
|
||||
return $messageKey;
|
||||
}
|
||||
|
||||
public function addError($message = null)
|
||||
{
|
||||
$this->errorBag = [
|
||||
'key' => $this->key,
|
||||
'message' => is_null($message) ? "{$this->key} cant be empty" : $this->parseMessage($message)
|
||||
];
|
||||
}
|
||||
|
||||
public function getParamValue()
|
||||
{
|
||||
if (array_key_exists($this->key, $this->paramBag)) {
|
||||
return $this->paramBag[$this->key];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
3
Aiko/Aiko/Libs/ValidatorRule.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/ValidatorRule.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
136
Aiko/Aiko/Libs/ValidatorRuleCollection.php
Normal file
136
Aiko/Aiko/Libs/ValidatorRuleCollection.php
Normal file
@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
use Exception;
|
||||
use Symfony\Component\HttpFoundation\File\UploadedFile;
|
||||
|
||||
class ValidatorRuleCollection
|
||||
{
|
||||
|
||||
private $allowedMimeType = [
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/jpg',
|
||||
'video/mp4',
|
||||
'application/pdf',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheetapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'application/msword',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
|
||||
'application/vnd.ms-word.document.macroEnabled.12',
|
||||
'application/vnd.ms-word.template.macroEnabled.12',
|
||||
'application/vnd.ms-excel',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
|
||||
'application/vnd.ms-excel.sheet.macroEnabled.12',
|
||||
'application/vnd.ms-excel.template.macroEnabled.12',
|
||||
'application/vnd.ms-excel.addin.macroEnabled.12',
|
||||
'application/vnd.ms-excel.sheet.binary.macroEnabled.12'
|
||||
];
|
||||
|
||||
/**
|
||||
* @param string $key pattern : mustMatch|param_key_match
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* $request = ['password' => '123456', 'password_confirmation' => '123456']
|
||||
* new Validator($params)->addRule('password', 'mustMatch|password_confirmation');
|
||||
*
|
||||
*/
|
||||
public function mustMatch($key, $ruleString, $value, $params)
|
||||
{
|
||||
$keys = explode('|', $ruleString);
|
||||
if (count($keys) < 2) {
|
||||
throw new Exception("validator rules not valid for $$ruleString");
|
||||
}
|
||||
$compare1 = $this->_getParamValue($keys[1], $params);
|
||||
$compare2 = $this->_getParamValue($key, $params);
|
||||
if (is_null($compare1) || is_null($compare2)) {
|
||||
return "VALIDATOR.MUST_MATCH.MUST_NOT_EMPTY";
|
||||
}
|
||||
if ($compare1 != $compare2) {
|
||||
return "VALIDATOR.MUST_MATCH.NOT_MATCH";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $key pattern : file|image,document|2048
|
||||
*
|
||||
* pattern for | : index 0 must be file, index 1 is file type, for the rest current support only maxSize
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* $request = ['my_file' => $file, 'others' => '1234']
|
||||
* new Validator($params)->addRule('my_file', 'file|image,document|2048');
|
||||
*
|
||||
*/
|
||||
public function file($key, $ruleString, $value, $params)
|
||||
{
|
||||
$log = new Log(0);
|
||||
|
||||
if (!($value instanceof UploadedFile)) {
|
||||
$log->error("ValidatorRuleCollection [file]: file is not file");
|
||||
return 'VALIDATOR.FILE.IS_NOT_FILE';
|
||||
}
|
||||
$keys = explode('|', $ruleString);
|
||||
if (count($keys) == 0) {
|
||||
throw new Exception("$key validator rules not valid for $$ruleString");
|
||||
}
|
||||
$validatedMime = [];
|
||||
if (strpos($keys[1], ',') == false) {
|
||||
if (!in_array($keys[1], ['image', 'document'])) {
|
||||
$log->error("ValidatorRuleCollection [file]: mime not supported {$keys[1]}");
|
||||
return 'VALIDATOR.FILE.MIME';
|
||||
}
|
||||
$validatedMime = [$keys[1]];
|
||||
} else {
|
||||
$exp = explode(',', $keys[1]);
|
||||
for ($i = 0; $i < count($exp); $i++) {
|
||||
if (!in_array($exp[$i], ['image', 'document'])) {
|
||||
$log->error("ValidatorRuleCollection [file]: mime not supported {$exp[$i]}");
|
||||
return 'VALIDATOR.FILE.MIME';
|
||||
}
|
||||
}
|
||||
$validatedMime = $exp;
|
||||
}
|
||||
$maxSize = 4096;
|
||||
if (isset($keys[2]) && is_numeric($keys[2])) {
|
||||
$maxSize = (int) $maxSize;
|
||||
}
|
||||
$sizeInKb = $value->getSize() / 1024;
|
||||
if ($sizeInKb > $maxSize) {
|
||||
$log->error("ValidatorRuleCollection [file]: max size {$sizeInKb} higher than allowed $maxSize");
|
||||
return "VALIDATOR.FILE.MAX_SIZE";
|
||||
}
|
||||
$mime = $value->getMimeType();
|
||||
if (in_array('image', $validatedMime)) {
|
||||
if (!in_array($mime, $this->allowedMimeType)) {
|
||||
$log->error("ValidatorRuleCollection [file]: image mime type not allowed $mime");
|
||||
return 'VALIDATOR.FILE.IMAGE_INVALID';
|
||||
}
|
||||
}
|
||||
if (in_array('document', $validatedMime)) {
|
||||
if (!in_array($mime, $this->allowedMimeType)) {
|
||||
$log->error("ValidatorRuleCollection [file]: document mime type not allowed $mime");
|
||||
return 'VALIDATOR.FILE.DOCUMENT_INVALID';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public function required($key, $ruleString, $value, $params)
|
||||
{
|
||||
if (!isset($value) || strlen($value) == 0) return 'VALIDATOR.REQUIRED';
|
||||
return null;
|
||||
}
|
||||
|
||||
public function _getParamValue($key, $params)
|
||||
{
|
||||
if (array_key_exists($key, $params)) {
|
||||
return $params[$key];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
570
Aiko/Aiko/Libs/WhatsApp.php
Normal file
570
Aiko/Aiko/Libs/WhatsApp.php
Normal file
@ -0,0 +1,570 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
use modules\endpoint\webhook\model\Webhook;
|
||||
use Aiko\Model;
|
||||
use Error;
|
||||
use PDOException;
|
||||
use ErrorException;
|
||||
use PDO;
|
||||
|
||||
class WhatsApp extends Model
|
||||
{
|
||||
/** @var $registry hcportal registry */
|
||||
protected $registry;
|
||||
|
||||
/** @var $sender phone number for sender */
|
||||
private $sender;
|
||||
|
||||
/** @var Client $client guzzle http client */
|
||||
private $client;
|
||||
|
||||
/** @var Array $messageType allowed message type */
|
||||
private $messageType = ['text', 'image', 'video', 'document'];
|
||||
|
||||
/**
|
||||
* constructor
|
||||
*
|
||||
* @param $registry hcportal registry
|
||||
* @param String|null $baseURL
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct($registry, $baseURL = null)
|
||||
{
|
||||
parent::__construct($registry);
|
||||
$this->init($baseURL);
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* init component
|
||||
*
|
||||
* @param String|null $baseURL
|
||||
*/
|
||||
private function init($baseURL = null)
|
||||
{
|
||||
$this->sender = $this->registry->config->whatsapp_sender;
|
||||
$this->client = new Client([
|
||||
'base_uri' => $baseURL ?? $this->registry->config->whatsapp_endpoint,
|
||||
'headers' => ['Authorization' => $this->registry->config->whatsapp_api_token, "Accept" => "application/json"],
|
||||
]);
|
||||
}
|
||||
|
||||
public function getTokenAccess(){
|
||||
|
||||
try{
|
||||
$client= new Client();
|
||||
$token='';
|
||||
if($this->registry->config->wa_token_need_reload){
|
||||
$data = array(
|
||||
'username'=>$this->registry->config->wa_username,
|
||||
'password'=>$this->registry->config->wa_password,
|
||||
'grant_type'=>$this->registry->config->wa_grant_type,
|
||||
'client_id'=>$this->registry->config->wa_client_id,
|
||||
'client_secret'=>$this->registry->config->wa_client_secret,
|
||||
);
|
||||
$response = $client->post($this->registry->config->wa_auth_url, [
|
||||
'headers' => ['Content-Type' => 'application/json', 'Accept' => 'application/json'],
|
||||
'body' => json_encode($data)
|
||||
]);
|
||||
$data=json_decode($response->getBody());
|
||||
|
||||
|
||||
$result=$this->_saveTokenAcces($data);
|
||||
|
||||
if(!$result){
|
||||
throw new ErrorException('failed save access token to db');
|
||||
}
|
||||
$token=$data->access_token;
|
||||
}else{
|
||||
$stmt=$this->registry->db->prepare('select access_token from wa_qontak_auth where `name`=:name');
|
||||
$stmt->bindValue(':name',$this->registry->config->wa_token_name,PDO::PARAM_STR);
|
||||
$stmt->execute();
|
||||
if($stmt->rowCount()==0){
|
||||
throw new ErrorException('token access empty');
|
||||
}
|
||||
$rs=$stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
$token=$rs[0]['access_token'];
|
||||
}
|
||||
|
||||
return $token;
|
||||
}catch(PDOException $e){
|
||||
$this->registry->log->error('WhatsApp/getTokenAccess:'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
|
||||
return false;
|
||||
}catch(ErrorException $e){
|
||||
$this->registry->log->error('WhatsApp/getTokenAccess:'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private function _saveTokenAcces($data){
|
||||
try{
|
||||
// $this->registry->db->beginTransaction();
|
||||
$stmtCheck=$this->registry->db->prepare("select id from `wa_qontak_auth` where name=:name");
|
||||
$stmtCheck->bindValue(':name',$this->registry->config->wa_token_name,PDO::PARAM_STR);
|
||||
$stmtCheck->execute();
|
||||
if($stmtCheck->rowCount()>0){
|
||||
$stmtUpdate=$this->registry->db->prepare('update `wa_qontak_auth` set access_token=:access_token,
|
||||
token_type=:token_type,
|
||||
expires_in=:expires_in,
|
||||
refresh_token=:refresh_token,
|
||||
created_at=:created_at where `name`=:name');
|
||||
$stmtUpdate->bindValue(':access_token',$data->access_token,PDO::PARAM_STR);
|
||||
$stmtUpdate->bindValue(':token_type',$data->token_type,PDO::PARAM_STR);
|
||||
$stmtUpdate->bindValue(':expires_in',$data->expires_in,PDO::PARAM_STR);
|
||||
$stmtUpdate->bindValue(':refresh_token',$data->refresh_token,PDO::PARAM_STR);
|
||||
$stmtUpdate->bindValue(':created_at',$data->created_at,PDO::PARAM_STR);
|
||||
$stmtUpdate->bindValue(':name',$this->registry->config->wa_token_name,PDO::PARAM_STR);
|
||||
$stmtUpdate->execute();
|
||||
}else{
|
||||
$stmtInsert=$this->registry->db->prepare('insert into `wa_qontak_auth` (
|
||||
access_token,
|
||||
token_type,
|
||||
expires_in,
|
||||
refresh_token,
|
||||
created_at,
|
||||
name
|
||||
)values
|
||||
(:access_token,
|
||||
:token_type,
|
||||
:expires_in,
|
||||
:refresh_token,
|
||||
:created_at,
|
||||
:name)');
|
||||
$stmtInsert->bindValue(':access_token',$data->access_token,PDO::PARAM_STR);
|
||||
$stmtInsert->bindValue(':token_type',$data->token_type,PDO::PARAM_STR);
|
||||
$stmtInsert->bindValue(':expires_in',$data->expires_in,PDO::PARAM_STR);
|
||||
$stmtInsert->bindValue(':refresh_token',$data->refresh_token,PDO::PARAM_STR);
|
||||
$stmtInsert->bindValue(':created_at',$data->created_at,PDO::PARAM_STR);
|
||||
$stmtInsert->bindValue(':name',$this->registry->config->wa_token_name,PDO::PARAM_STR);
|
||||
$stmtInsert->execute();
|
||||
}
|
||||
// $this->registry->db->commit();
|
||||
return true;
|
||||
|
||||
}catch(PDOException $e){
|
||||
$this->registry->db->rollBack();
|
||||
$this->registry->log->error('WhatsApp/_saveTokenAcces:'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
|
||||
return false;
|
||||
}catch(ErrorException $e){
|
||||
$this->registry->db->rollBack();
|
||||
$this->registry->log->error('WhatsApp/_saveTokenAcces:'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* set sender
|
||||
|
||||
* @param String $sender phone number
|
||||
*
|
||||
* @return Aiko\Whatsapp
|
||||
*
|
||||
*/
|
||||
public function setSender($sender)
|
||||
{
|
||||
$this->sender = $sender;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send message to many recepient
|
||||
*
|
||||
* @param Array $payload
|
||||
* example of param
|
||||
* [
|
||||
* [
|
||||
* 'phone' => '081xxx',
|
||||
* 'message' => 'hi',
|
||||
* 'link' => 'https://xxxx',
|
||||
* 'type' => 'image' // default text-only
|
||||
* ]
|
||||
* ]
|
||||
*/
|
||||
public function sendBulkMessage($payload = [])
|
||||
{
|
||||
if (!is_array($payload)) {
|
||||
$this->registry->log->customError('WhatsApp', "Parameter must be an array");
|
||||
return false;
|
||||
}
|
||||
|
||||
$report = [];
|
||||
foreach ($payload as $value) {
|
||||
$send = $this->sendMessage($value['phone'], $value['message'], $value['type'], $value['link']);
|
||||
array_push($report, $send);
|
||||
}
|
||||
|
||||
return $report;
|
||||
}
|
||||
|
||||
public function sendBulkMessageQontak($payload = [])
|
||||
{
|
||||
|
||||
if (!is_array($payload)) {
|
||||
$this->registry->log->customError('WhatsApp', "Parameter must be an array");
|
||||
return false;
|
||||
}
|
||||
|
||||
$report = [];
|
||||
foreach ($payload as $value) {
|
||||
|
||||
$send = $this->sendMessageQontak($value['phone'], $value['name'],$value['parameter'], $value['template']);
|
||||
array_push($report, $send);
|
||||
}
|
||||
|
||||
return $report;
|
||||
}
|
||||
|
||||
public function sendMessage($toNumber, $message, $type = 'text', $link = null)
|
||||
{
|
||||
if (!in_array($type, $this->messageType)) {
|
||||
$this->registry->log->customError('WhatsApp', "Message type not allowed : $type");
|
||||
return false;
|
||||
}
|
||||
|
||||
$endpoint = 'send-message';
|
||||
$payload = array(
|
||||
'phone' => $toNumber,
|
||||
'message' => $message,
|
||||
'secret' => false, // or true
|
||||
'priority' => false, // or true
|
||||
);
|
||||
switch ($type) {
|
||||
case 'image':
|
||||
$endpoint = 'send-image';
|
||||
$payload = array(
|
||||
'phone' => $toNumber,
|
||||
'caption' => $message,
|
||||
'image' => $link,
|
||||
'secret' => false, // or true
|
||||
'priority' => false, // or true
|
||||
);
|
||||
break;
|
||||
case 'video':
|
||||
$endpoint = 'send-video';
|
||||
$payload = array(
|
||||
'phone' => $toNumber,
|
||||
'caption' => $message,
|
||||
'document' => $link,
|
||||
'secret' => false, // or true
|
||||
'priority' => false, // or true
|
||||
);
|
||||
break;
|
||||
case 'document':
|
||||
$endpoint = 'send-document';
|
||||
$payload = array(
|
||||
'phone' => $toNumber,
|
||||
'document' => $link,
|
||||
'secret' => false, // or true
|
||||
'priority' => false, // or true
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
// $request = $this->client->post($endpoint, array('form_params' => $payload));
|
||||
// $response = $request->getBody();
|
||||
// $contents = json_decode($response->getContents());
|
||||
|
||||
// if ($contents) {
|
||||
// $webhook = new Webhook($this->registry);
|
||||
// if (isset($contents->data)) {
|
||||
// $data = $contents->data->message;
|
||||
// foreach ($data as $value) {
|
||||
// $webhook->create([
|
||||
// 'phone' => $value->phone,
|
||||
// 'status' => $value->status,
|
||||
// 'note' => $value->text,
|
||||
// 'id' => $value->id,
|
||||
// 'deviceId' => $this->registry->config->whatsapp_device_id,
|
||||
// ]);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// return $contents;
|
||||
return true;
|
||||
}
|
||||
|
||||
public function sendMessageQontak($toNumber, $toName,$parameters, $templateName)
|
||||
{
|
||||
// try{
|
||||
// // $toNumber='+6282214258200';
|
||||
// $tokenAccess=$this->getTokenAccess();
|
||||
// $client = new Client();
|
||||
// // var_dump($templateName);
|
||||
// // var_dump($this->_getTemplateId($templateName));
|
||||
// // exit();
|
||||
// $templateID=$this->_getTemplateId($templateName);
|
||||
|
||||
|
||||
// if($templateID===-1){
|
||||
// $this->registry->log->error('template tidak active atau belum ada dengan templateName:'.$templateName.', user: '.\Helper::getSessionVar('username'));
|
||||
// return true;
|
||||
// }
|
||||
|
||||
// $data=array(
|
||||
// "to_name"=>$toName,
|
||||
// "to_number"=>\Helper::formatPhoneNumber($toNumber),
|
||||
// "message_template_id"=>$templateID,
|
||||
// "channel_integration_id"=>$this->registry->config->channel_integration_id,
|
||||
// "language"=> array(
|
||||
// "code"=> "id"
|
||||
// ),
|
||||
// "parameters"=>array(
|
||||
// "body"=>$parameters
|
||||
// )
|
||||
// );
|
||||
|
||||
// $client = new Client();
|
||||
// $request = $client->request('POST', $this->registry->config->whatsapp_endpoint, [
|
||||
// 'headers' => [
|
||||
// 'Authorization' => 'Bearer '.$tokenAccess,
|
||||
// 'Content-Type' => 'application/json', 'Accept' => 'application/json'],
|
||||
// 'body' => json_encode($data)]
|
||||
// );
|
||||
// $response = $client->send($request);
|
||||
// dd($response->json());
|
||||
|
||||
|
||||
// $response = $client->post($this->registry->config->whatsapp_endpoint, [
|
||||
// 'headers' => [
|
||||
// 'Authorization' => 'Bearer '.$tokenAccess,
|
||||
// 'Content-Type' => 'application/json', 'Accept' => 'application/json'],
|
||||
// 'body' => json_encode($data)
|
||||
// ]);
|
||||
|
||||
// var_dump(json_encode($responseData));
|
||||
// exit();
|
||||
// $responseData=json_decode($response->getBody());
|
||||
|
||||
// if(property_exists($responseData,'status')){
|
||||
// if(!$responseData->status=='success'){
|
||||
// throw new ErrorException('Gagal kirim WA');
|
||||
// }
|
||||
// }else{
|
||||
// throw new ErrorException('Gagal kirim WA, response undefined');
|
||||
// }
|
||||
// return true;
|
||||
// }catch(ErrorException $e){
|
||||
// $this->registry->log->error('WhatsApp/sendMessageQontak:'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
|
||||
// return false;
|
||||
// }
|
||||
|
||||
try {
|
||||
|
||||
$tokenAccess=$this->getTokenAccess();
|
||||
$client = new Client();
|
||||
$templateID=$this->_getTemplateId($templateName);
|
||||
|
||||
|
||||
if($templateID===-1){
|
||||
$this->registry->log->error('template tidak active atau belum ada dengan templateName:'.$templateName.', user: '.\Helper::getSessionVar('username'));
|
||||
return true;
|
||||
}
|
||||
|
||||
$data=array(
|
||||
"to_name"=>$toName,
|
||||
"to_number"=>\Helper::formatPhoneNumber($toNumber),
|
||||
"message_template_id"=>$templateID,
|
||||
"channel_integration_id"=>$this->registry->config->channel_integration_id,
|
||||
"language"=> array(
|
||||
"code"=> "id"
|
||||
),
|
||||
"parameters"=>array(
|
||||
"body"=>$parameters
|
||||
)
|
||||
);
|
||||
|
||||
$request = $client->post($this->registry->config->whatsapp_endpoint, [
|
||||
'headers' => [
|
||||
'Authorization' => 'Bearer '.$tokenAccess,
|
||||
'Content-Type' => 'application/json', 'Accept' => 'application/json'],
|
||||
'body' => json_encode($data)
|
||||
]);
|
||||
|
||||
$this->response = json_decode($request->getBody()->getContents());
|
||||
return true;
|
||||
} catch (\GuzzleHttp\Exception\RequestException $e) {
|
||||
$this->errors = json_decode($e->getResponse()->getBody()->getContents());
|
||||
$this->registry->log->error('WhatsApp/sendMessageQontak:'.$this->errors->error->messages[0].', user: '.\Helper::getSessionVar('username'));
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
private function _getTemplateId($name){
|
||||
try{
|
||||
$stmt=$this->registry->db->prepare('select id from wa_templates where `name`=:templateName');
|
||||
$stmt->bindValue(':templateName',$name,PDO::PARAM_STR);
|
||||
$stmt->execute();
|
||||
if($stmt->rowCount()==0){
|
||||
// throw new ErrorException('template id dengan name :'.$name.' kosong');
|
||||
//jika template tidak ada return -1 bisa jadi sudah di non activekan
|
||||
return -1;
|
||||
}
|
||||
$rs=$stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
return $rs[0]['id'];
|
||||
}catch(PDOException $e){
|
||||
$this->registry->log->error('WhatsApp/_getTemplateId:'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
|
||||
return false;
|
||||
}catch(ErrorException $e){
|
||||
$this->registry->log->error('WhatsApp/_getTemplateId:'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function sendDocumentLocally($toNumber, $filePath, $config)
|
||||
{
|
||||
$handle = fopen($filePath, "r");
|
||||
$file = fread($handle, filesize($filePath));
|
||||
$config['size'] = filesize($filePath);
|
||||
$endpoint = 'send-document-from-local';
|
||||
$payload = array(
|
||||
'phone' => $toNumber,
|
||||
'file' => base64_encode($file),
|
||||
'data' => json_encode($config),
|
||||
);
|
||||
|
||||
$request = $this->client->post($endpoint, array('form_params' => $payload));
|
||||
$response = $request->getBody();
|
||||
$contents = json_decode($response->getContents());
|
||||
|
||||
return $contents;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send message to many recepient in very sumple terms
|
||||
*
|
||||
* @param Array $payload
|
||||
* example of param
|
||||
* [
|
||||
* [
|
||||
* 'phone' => '081xxx',
|
||||
* 'message' => 'hi',
|
||||
* 'secret' => false,
|
||||
* 'priority' => false
|
||||
* ]
|
||||
* ]
|
||||
*/
|
||||
public function simpleBulkMessage($params = [])
|
||||
{
|
||||
$endpoint = 'v2/send-bulk/text';
|
||||
$request = $this->client->post($endpoint, array('body' => json_encode($params)));
|
||||
$response = $request->getBody();
|
||||
$contents = json_decode($response->getContents());
|
||||
|
||||
return $contents;
|
||||
}
|
||||
public function sendDocument($toNumber, $urlPath, $caption = '')
|
||||
{
|
||||
// $endpoint = 'send-document';
|
||||
// $payload = array(
|
||||
// 'phone' => $toNumber,
|
||||
// 'document' => $urlPath,
|
||||
// 'caption' => $caption,
|
||||
// 'isGroup' => false,
|
||||
// );
|
||||
|
||||
// $request = $this->client->post($endpoint, array('form_params' => $payload));
|
||||
// $response = $request->getBody();
|
||||
// $contents = json_decode($response->getContents());
|
||||
|
||||
// return $contents;
|
||||
return true;
|
||||
}
|
||||
|
||||
public function sendDocumentQontak($toNumber, $toName,$parameters, $templateName,$header)
|
||||
{
|
||||
try{
|
||||
|
||||
$tokenAccess=$this->getTokenAccess();
|
||||
$client = new Client();
|
||||
// var_dump($templateName);
|
||||
// var_dump($this->_getTemplateId($templateName));
|
||||
// exit();
|
||||
$data=array(
|
||||
"to_name"=>$toName,
|
||||
"to_number"=>\Helper::formatPhoneNumber($toNumber),
|
||||
"message_template_id"=>$this->_getTemplateId($templateName),
|
||||
"channel_integration_id"=>$this->registry->config->channel_integration_id,
|
||||
"language"=> array(
|
||||
"code"=> "id"
|
||||
),
|
||||
"parameters"=>array(
|
||||
"header"=> $header,
|
||||
"body"=>$parameters
|
||||
)
|
||||
);
|
||||
$response = $client->post($this->registry->config->whatsapp_endpoint, [
|
||||
'headers' => [
|
||||
'Authorization' => 'Bearer '.$tokenAccess,
|
||||
'Content-Type' => 'application/json', 'Accept' => 'application/json'],
|
||||
'body' => json_encode($data)
|
||||
]);
|
||||
$responseData=json_decode($response->getBody());
|
||||
if(property_exists($responseData,'status')){
|
||||
if(!$responseData->status=='success'){
|
||||
throw new ErrorException('Gagal kirim WA');
|
||||
}
|
||||
}else{
|
||||
throw new ErrorException('Gagal kirim WA, response undefined');
|
||||
}
|
||||
return true;
|
||||
}catch(ErrorException $e){
|
||||
$this->registry->log->error('WhatsApp/sendDocumentQontak:'.$e->getMessage().', user: '.\Helper::getSessionVar('username'));
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public function sendMessageQontakTermination($toNumber, $toName,$parameters, $templateName)
|
||||
{
|
||||
try {
|
||||
|
||||
$tokenAccess=$this->getTokenAccess();
|
||||
$client = new Client();
|
||||
$templateID=$this->_getTemplateId($templateName);
|
||||
|
||||
|
||||
if($templateID===-1){
|
||||
$this->registry->log->error('template tidak active atau belum ada dengan templateName:'.$templateName.', user: '.\Helper::getSessionVar('username'));
|
||||
return true;
|
||||
}
|
||||
|
||||
$data=array(
|
||||
"to_name"=>$toName,
|
||||
"to_number"=>\Helper::formatPhoneNumber($toNumber),
|
||||
"message_template_id"=>$templateID,
|
||||
"channel_integration_id"=>$this->registry->config->channel_integration_id,
|
||||
"language"=> array(
|
||||
"code"=> "id"
|
||||
),
|
||||
"parameters"=>array(
|
||||
"body"=>$parameters
|
||||
)
|
||||
);
|
||||
|
||||
$request = $client->post($this->registry->config->whatsapp_endpoint, [
|
||||
'headers' => [
|
||||
'Authorization' => 'Bearer '.$tokenAccess,
|
||||
'Content-Type' => 'application/json', 'Accept' => 'application/json'],
|
||||
'body' => json_encode($data)
|
||||
]);
|
||||
|
||||
$this->response = json_decode($request->getBody()->getContents());
|
||||
return $this->response;
|
||||
} catch (\GuzzleHttp\Exception\RequestException $e) {
|
||||
// $this->registry->log->error('WhatsApp/sendMessageQontak:'.$this->errors->error->messages[0].', user: '.\Helper::getSessionVar('username'));
|
||||
$this->errors = json_decode($e->getResponse()->getBody()->getContents());
|
||||
return $this->errors;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
3
Aiko/Aiko/Libs/WhatsApp.php:Zone.Identifier
Normal file
3
Aiko/Aiko/Libs/WhatsApp.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
831
Aiko/Framework/Core.php
Normal file
831
Aiko/Framework/Core.php
Normal file
@ -0,0 +1,831 @@
|
||||
<?php
|
||||
|
||||
namespace Aiko;
|
||||
|
||||
use Aiko\Database\Connections;
|
||||
use Aiko\Http;
|
||||
use Aiko\Token;
|
||||
use modules\rule\model\Rule;
|
||||
use Predis\Client;
|
||||
use Predis\Session\Handler;
|
||||
use Aiko\SessionRedis;
|
||||
|
||||
class Registry
|
||||
{
|
||||
private $vars = array();
|
||||
public function __set($index, $value)
|
||||
{
|
||||
$this->vars[$index] = $value;
|
||||
}
|
||||
public function __get($index)
|
||||
{
|
||||
return $this->vars[$index];
|
||||
}
|
||||
}
|
||||
|
||||
abstract class Controller
|
||||
{
|
||||
protected $registry;
|
||||
public $ActionAjaxOff;
|
||||
protected $methodAccess;
|
||||
protected $apiAction;
|
||||
protected $apiParams;
|
||||
protected $apiModule;
|
||||
protected $publicAction = array();
|
||||
private $allowJwt = array();
|
||||
protected $appID;
|
||||
protected $tokenID;
|
||||
protected $generalActions=array();
|
||||
|
||||
protected $isFile=false;
|
||||
|
||||
private $allowedMimeType = [
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/jpg',
|
||||
'video/mp4',
|
||||
'application/pdf',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheetapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'text/plain',
|
||||
'application/octet-stream',
|
||||
'application/zip',
|
||||
'application/msword',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
|
||||
'application/vnd.ms-word.document.macroEnabled.12',
|
||||
'application/vnd.ms-word.template.macroEnabled.12',
|
||||
'application/vnd.ms-excel',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
|
||||
'application/vnd.ms-excel.sheet.macroEnabled.12',
|
||||
'application/vnd.ms-excel.template.macroEnabled.12',
|
||||
'application/vnd.ms-excel.addin.macroEnabled.12',
|
||||
'application/vnd.ms-excel.sheet.binary.macroEnabled.12'
|
||||
];
|
||||
|
||||
public function __construct($registry)
|
||||
{
|
||||
// session_id('hcportal-session-id');
|
||||
// session_start();
|
||||
// Http::enabledCors();
|
||||
|
||||
$this->registry = $registry;
|
||||
$this->methodAccess = $_SERVER['REQUEST_METHOD'];
|
||||
$this->allowJwt = array('dologin', 'dologout', 'refreshToken', 'generateNewToken', 'loginauth');
|
||||
|
||||
|
||||
// connect main DB
|
||||
// $this->registry = $registry;
|
||||
// $this->registry->db = Connections::getInstance(
|
||||
// $this->registry->config->host,
|
||||
// $this->registry->config->db,
|
||||
// $this->registry->config->socket,
|
||||
// $this->registry->config->user,
|
||||
// $this->registry->config->password,
|
||||
// $this->registry->config->dbms
|
||||
// );
|
||||
|
||||
if($this->registry->config->dbMainConType!=='local')
|
||||
{
|
||||
$this->registry->db = Connections::getInstance($this->registry->config->dbMainConType);
|
||||
}else {
|
||||
$this->registry->db = Connections::getInstance(
|
||||
$this->registry->config->dbMainConType,
|
||||
$this->registry->config->host,
|
||||
$this->registry->config->socket,
|
||||
$this->registry->config->user,
|
||||
$this->registry->config->password
|
||||
);
|
||||
}
|
||||
|
||||
// $handler = new Session($registry);
|
||||
// $result= session_set_save_handler($handler,true);
|
||||
|
||||
// session_start();
|
||||
// session_start();
|
||||
|
||||
|
||||
// if (!interface_exists('SessionHandlerInterface')) {
|
||||
// exit('ATTENTION: the session handler implemented by Predis requires PHP >= 5.4.0 ' .
|
||||
// "or a polyfill for SessionHandlerInterface provided by an external package.\n");
|
||||
// }
|
||||
// $single_server=[
|
||||
// 'scheme' => 'tcp',
|
||||
// 'host' => '10.1.200.218',
|
||||
// 'port' => 6388,
|
||||
// ];
|
||||
// $client = new Client($single_server, ['prefix' => 'sessions:']);
|
||||
|
||||
// // Set `gc_maxlifetime` to specify a time-to-live of 5 seconds for session keys.
|
||||
// $handler = new Handler($client, ['gc_maxlifetime' => get_cfg_var("session.gc_maxlifetime")]);
|
||||
|
||||
// // Register the session handler.
|
||||
// $handler->register();
|
||||
|
||||
// // We just set a fixed session ID only for the sake of our example.
|
||||
// session_id('hcportalsessionid');
|
||||
|
||||
if(!isset($_SESSION))
|
||||
{
|
||||
session_start();
|
||||
}
|
||||
// check mime_type
|
||||
$this->checkContentFile();
|
||||
|
||||
|
||||
}
|
||||
|
||||
abstract public function index();
|
||||
|
||||
protected function checkToken()
|
||||
{
|
||||
try {
|
||||
$token = Http::getTokenJWT();
|
||||
|
||||
|
||||
// get token ID
|
||||
$tokenPart = explode('.', $token);
|
||||
|
||||
if (count($tokenPart) != 4) {
|
||||
throw new \ErrorException('token part invalid');
|
||||
}
|
||||
|
||||
$stmt = $this->registry->db->prepare('select appID,tokenID,chipper,data,expired from jwt where id=:id');
|
||||
$stmt->bindValue(':id', $tokenPart[3], \PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
$rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
|
||||
|
||||
if (count($rs) == 0) {
|
||||
throw new \ErrorException('token jwt not exist');
|
||||
}
|
||||
|
||||
$this->appID=$rs[0]['appID'];
|
||||
$this->tokenID=$rs[0]['tokenID'];
|
||||
|
||||
$now = time();
|
||||
if ($rs[0]['expired'] < $now) {
|
||||
throw new \Exception('Time Token refresh Exceded');
|
||||
}
|
||||
|
||||
// update expired
|
||||
$stmt = $this->registry->db->prepare('update jwt set expired=:expired where id=:id');
|
||||
$stmt->bindValue(':id', $tokenPart[3], \PDO::PARAM_INT);
|
||||
$stmt->bindValue(':expired', time() + __LIFETIMEJWT, \PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
|
||||
$newToken = $tokenPart[0] . '.' . $tokenPart[1] . '.' . $tokenPart[2];
|
||||
|
||||
$data = Token::decodeJWTNew($newToken, $rs[0]['chipper']);
|
||||
if (is_numeric($data)) {
|
||||
if ($data === 8) // expired token
|
||||
{
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token : expired token , token :' . $data);
|
||||
Http::tokenExpired(array('message' => 'Token need refresh'));
|
||||
} else {
|
||||
throw new \ErrorException('decode Error token :' . $data);
|
||||
}
|
||||
}
|
||||
$rData = json_decode(json_encode($data->data), true);
|
||||
\Helper::setSession($rData);
|
||||
return true;
|
||||
} catch (\ErrorException $e) {
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token :' . $e->getMessage());
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Wrong Token'));
|
||||
//return false;
|
||||
} catch (\Exception $e) {
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token :' . $e->getMessage());
|
||||
Http::UnauthorizedResponseJson(array('message' => $e->getMessage()));
|
||||
} catch (\PDOException $e) {
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token :' . $e->getMessage());
|
||||
Http::UnauthorizedResponseJson(array('message' => 'query error '));
|
||||
}
|
||||
}
|
||||
protected function checkTokenOld()
|
||||
{
|
||||
try {
|
||||
$token = Http::getTokenJWT();
|
||||
|
||||
|
||||
|
||||
$data = Token::decodeJWTNew($token);
|
||||
if (is_numeric($data)) {
|
||||
if ($data === 8) // expired token
|
||||
{
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token : expired token , token :' . $data);
|
||||
Http::tokenExpired(array('message' => 'Wrong Token'));
|
||||
} else {
|
||||
throw new \ErrorException('decode Error token :' . $data);
|
||||
}
|
||||
}
|
||||
$rData = json_decode(json_encode($data->data), true);
|
||||
\Helper::setSession($rData);
|
||||
return true;
|
||||
} catch (\ErrorException $e) {
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token :' . $e->getMessage());
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Wrong Token'));
|
||||
//return false;
|
||||
} catch (\Exception $e) {
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token :' . $e->getMessage());
|
||||
Http::UnauthorizedResponseJson(array('message' => $e->getMessage()));
|
||||
} catch (\PDOException $e) {
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token :' . $e->getMessage());
|
||||
Http::UnauthorizedResponseJson(array('message' => 'query error '));
|
||||
}
|
||||
}
|
||||
|
||||
protected function checkRulesAccess()
|
||||
{
|
||||
$rule = new Rule($this->registry);
|
||||
if (!in_array($this->apiAction, $this->publicAction)) {
|
||||
$hasAccess = $rule->hasAccess($this->apiModule, $this->apiAction);
|
||||
|
||||
if ($hasAccess == false) {
|
||||
Http::ErrorQueryResponse('operation not permit', 'json');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected function checkAPIAccess()
|
||||
{
|
||||
|
||||
/* check method access */
|
||||
$this->allowOptionMethod();
|
||||
|
||||
if (!in_array($this->methodAccess, array('POST', 'GET', 'DELETE'))) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Method Not allowed'));
|
||||
}
|
||||
$this->apiAction = '';
|
||||
switch ($this->methodAccess) {
|
||||
case 'POST':
|
||||
/* check and get action */
|
||||
$this->apiAction = Http::GetvarData('action');
|
||||
if (!isset($this->apiAction)) {
|
||||
$jtext = Http::GetBodyRequest();
|
||||
$this->apiParams = \Firebase\JWT\JWT::jsonDecode($jtext);
|
||||
if (!isset($this->apiParams->action)) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Action not set'));
|
||||
}
|
||||
$this->apiAction = $this->apiParams->action;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
// GET // DELETE
|
||||
$this->apiAction = Http::GetvarData('action');
|
||||
if (strlen($this->apiAction) === 0) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Action not set'));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
/* check token */
|
||||
$isAllowed = $this->checkToken();
|
||||
if (!$isAllowed) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Wrong Token'));
|
||||
}
|
||||
|
||||
/* check rule */
|
||||
$this->checkRulesAccess();
|
||||
}
|
||||
|
||||
protected function isAuthorized()
|
||||
{
|
||||
/* check method access */
|
||||
$this->allowOptionMethod();
|
||||
|
||||
if (!in_array($this->methodAccess, array('POST', 'GET', 'DELETE'))) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Method Not allowed'));
|
||||
}
|
||||
$this->apiAction = '';
|
||||
|
||||
// var_dump($this->methodAccess);
|
||||
|
||||
switch ($this->methodAccess) {
|
||||
case 'POST':
|
||||
/* check and get action */
|
||||
if($this->isFile){
|
||||
$aText['action']=Http::GetVarData('action','post');
|
||||
$this->apiParams=\Firebase\JWT\JWT::jsonDecode(\Firebase\JWT\JWT::jsonEncode($aText));
|
||||
$this->apiAction = Http::GetVarData('action','post');
|
||||
}else{
|
||||
$jtext = Http::GetBodyRequest();
|
||||
$this->apiParams = \Firebase\JWT\JWT::jsonDecode($jtext);
|
||||
|
||||
if (!isset($this->apiParams->action)) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Action not set'));
|
||||
}
|
||||
|
||||
$this->apiAction = $this->apiParams->action;
|
||||
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
// GET // DELETE
|
||||
$this->apiAction = Http::GetvarData('action');
|
||||
$this->apiParams = json_decode(json_encode(Http::getAllRequest()));
|
||||
if (strlen($this->apiAction) === 0) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Action not set'));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if (!in_array($this->apiAction, $this->allowJwt)) {
|
||||
/* check token */
|
||||
$isAllowed = $this->checkToken();
|
||||
if (!$isAllowed) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Wrong Token'));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (is_array($this->generalActions)) {
|
||||
/* check rule */
|
||||
if(!in_array($this->apiAction,$this->generalActions)){
|
||||
$this->checkRulesAccess();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* process request */
|
||||
$this->prosesRequest();
|
||||
}
|
||||
|
||||
protected function checkAPIAccessEvaluation()
|
||||
{
|
||||
if ($this->methodAccess == 'OPTIONS') {
|
||||
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
|
||||
Http::ResponseJson('ok', '0', '1');
|
||||
}
|
||||
}
|
||||
$isAllowed = $this->checkTokenEvaluation();
|
||||
if (!$isAllowed) {
|
||||
Http::UnauthorizedResponseJson(array('message' => 'Wrong Token'));
|
||||
}
|
||||
}
|
||||
|
||||
protected function checkTokenEvaluation()
|
||||
{
|
||||
try {
|
||||
|
||||
$token = Http::getTokenJWT();
|
||||
$data = Token::decodeJWT($token);
|
||||
if (!isset($data->data)) {
|
||||
throw new \ErrorException('decode Error token :' . $token);
|
||||
}
|
||||
|
||||
$_SESSION = array();
|
||||
session_destroy();
|
||||
|
||||
$_SESSION['group'] = $data->data->group;
|
||||
$_SESSION['username'] = $data->data->username;
|
||||
$_SESSION['name'] = isset($data->data->name) ? $data->data->name : $data->data->nama;
|
||||
$_SESSION['section'] = isset($data->data->section) ? $data->data->section : $data->data->secion;
|
||||
$_SESSION['userID'] = $data->data->userID;
|
||||
$_SESSION['empNo'] = isset($data->data->empNo) ? $data->data->empNo : '';
|
||||
$_SESSION['empSite'] = $data->data->empSite;
|
||||
$_SESSION['empSubArea'] = isset($data->data->empSubArea) ? $data->data->empSubArea : '';
|
||||
$_SESSION['flagApp'] = isset($data->data->flagApp) ? $data->data->flagApp : '';
|
||||
$_SESSION['nationality'] = isset($data->data->nationality) ? $data->data->nationality : '';
|
||||
$_SESSION['role'] = isset($data->data->role) ? $data->data->role : '';
|
||||
|
||||
// if jwt valid set session var
|
||||
|
||||
return true;
|
||||
} catch (\ErrorException $e) {
|
||||
$this->registry->log->error('Module Controller / check Token Eval :' . $e->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
protected function allowOptionMethod()
|
||||
{
|
||||
if ($this->methodAccess == 'OPTIONS') {
|
||||
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
|
||||
Http::ResponseJson(array('ok'), '0', '1');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function prosesRequest()
|
||||
{
|
||||
switch ($this->methodAccess) {
|
||||
case 'POST':
|
||||
$this->executePost();
|
||||
break;
|
||||
case 'GET':
|
||||
$this->executeGet();
|
||||
break;
|
||||
case 'DELETE':
|
||||
$this->executeDelete();
|
||||
break;
|
||||
default:
|
||||
Http::ErrorQueryResponse('method not permit');
|
||||
break;
|
||||
}
|
||||
}
|
||||
protected function executePost()
|
||||
{
|
||||
$act = $this->apiAction;
|
||||
if (method_exists($this, $act)) {
|
||||
$this->$act();
|
||||
} else {
|
||||
Http::ErrorQueryResponse('Action not registered');
|
||||
}
|
||||
}
|
||||
private function executeGet()
|
||||
{
|
||||
$act = $this->apiAction;
|
||||
if (method_exists($this, $act)) {
|
||||
$this->$act();
|
||||
} else {
|
||||
Http::ErrorQueryResponse('Action not registered');
|
||||
}
|
||||
}
|
||||
protected function executeDelete()
|
||||
{
|
||||
}
|
||||
|
||||
protected function extendAllowJwt(array $extended)
|
||||
{
|
||||
foreach ($extended as $value) {
|
||||
array_push($this->allowJwt, $value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* fungsi ini untuk convert message dari api.
|
||||
* untuk keperluan migrasi FE ke framework yang baru
|
||||
* karena fokus utama migrasi FE dulu jadi BE yang menyesuaikan
|
||||
*
|
||||
* @param message
|
||||
* @return $result : string
|
||||
*/
|
||||
protected function convertMessages($message)
|
||||
{
|
||||
$result = $message;
|
||||
switch($message){
|
||||
case 'PAYROLL.MESSAGE.SUCCMESINS':
|
||||
$result = 'MESSAGE.SUCCMESINS';
|
||||
break;
|
||||
case 'PAYROLL.MESSAGE.FAILMESEXIST':
|
||||
$result = 'MESSAGE.DATA_ALREADY_EXIST';
|
||||
break;
|
||||
case 'PAYROLL.MESSAGE.FAILMESUNKNOWN':
|
||||
$result = 'MESSAGE.FAILMESUNKNOWN';
|
||||
break;
|
||||
case 'PAYROLL.MESSAGE.FAILMESERRREQ':
|
||||
$result = 'MESSAGE.FAILMESERRREQ';
|
||||
break;
|
||||
case 'PAYROLL.MESSAGE.SUCCMESDEL':
|
||||
$result = 'MESSAGE.SUCCMESDEL';
|
||||
break;
|
||||
case 'PAYROLL.MESSAGE.SUCCMESUPD':
|
||||
$result = 'MESSAGE.SUCCMESUPD';
|
||||
break;
|
||||
case 'PAYROLL.MESSAGE.FAILMESQUERY':
|
||||
$result = 'MESSAGE.FAILMESQUERY';
|
||||
break;
|
||||
case 'MENU.MASTER_DATA.ADMINISTRATIVE_AREA.MAIN.CANTDELETE':
|
||||
$result = 'MESSAGE.CANTDELETE';
|
||||
break;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* fungsi ini untuk convert response menjadi format pagination.
|
||||
* untuk keperluan migrasi FE ke framework yang baru
|
||||
* karena fokus utama migrasi FE dulu jadi BE yang menyesuaikan
|
||||
*
|
||||
* @param array
|
||||
* @return array
|
||||
*/
|
||||
protected function convertToPaginationFormat($array)
|
||||
{
|
||||
$total = count($array);
|
||||
$aData['iTotalDisplayRecords'] = $total;
|
||||
$aData['iTotalRecords'] = $total;
|
||||
$aData['aData'] = $array;
|
||||
|
||||
return $aData;
|
||||
}
|
||||
|
||||
private function checkContentFile(){
|
||||
$this->isFile=Http::isMultipartFormData();
|
||||
if($this->isFile){
|
||||
if (!empty($_FILES) && is_array($_FILES) && count($_FILES) > 0) {
|
||||
foreach ($_FILES as $file) {
|
||||
$filepath = $file['tmp_name'];
|
||||
// $filesize = filesize($filepath);
|
||||
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
|
||||
$filetype = finfo_file($fileinfo, $filepath);
|
||||
finfo_close($fileinfo);
|
||||
if (!in_array($filetype, $this->allowedMimeType)) {
|
||||
Http::ErrorQueryResponse(array('name' => $file['name'], 'message' =>'15220-failed'), 'json');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected function setSession($token)
|
||||
{
|
||||
// get token ID
|
||||
$tokenPart = explode('.', $token);
|
||||
\Helper::dump($tokenPart);
|
||||
if (count($tokenPart) != 4) {
|
||||
throw new \ErrorException('token part invalid');
|
||||
}
|
||||
|
||||
$stmt = $this->registry->db->prepare('select appID,tokenID,chipper,data,expired from jwt where id=:id');
|
||||
$stmt->bindValue(':id', $tokenPart[3], \PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
$rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
|
||||
|
||||
if (count($rs) == 0) {
|
||||
throw new \ErrorException('token jwt not exist');
|
||||
}
|
||||
|
||||
$this->appID=$rs[0]['appID'];
|
||||
$this->tokenID=$rs[0]['tokenID'];
|
||||
|
||||
$now = time();
|
||||
if ($rs[0]['expired'] < $now) {
|
||||
throw new \Exception('Time Token refresh Exceded');
|
||||
}
|
||||
|
||||
// update expired
|
||||
$stmt = $this->registry->db->prepare('update jwt set expired=:expired where id=:id');
|
||||
$stmt->bindValue(':id', $tokenPart[3], \PDO::PARAM_INT);
|
||||
$stmt->bindValue(':expired', time() + __LIFETIMEJWT, \PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
|
||||
$newToken = $tokenPart[0] . '.' . $tokenPart[1] . '.' . $tokenPart[2];
|
||||
|
||||
$data = Token::decodeJWTNew($newToken, $rs[0]['chipper']);
|
||||
if (is_numeric($data)) {
|
||||
if ($data === 8) // expired token
|
||||
{
|
||||
$this->registry->log->customError('tokenError', 'Module Controller / check Token : expired token , token :' . $data);
|
||||
Http::tokenExpired(array('message' => 'Token need refresh'));
|
||||
} else {
|
||||
throw new \ErrorException('decode Error token :' . $data);
|
||||
}
|
||||
}
|
||||
$rData = json_decode(json_encode($data->data), true);
|
||||
\Helper::setSession($rData);
|
||||
}
|
||||
}
|
||||
|
||||
class Router
|
||||
{
|
||||
private $registry;
|
||||
private $path;
|
||||
private $args = array();
|
||||
public $file;
|
||||
public $controller;
|
||||
public $action;
|
||||
public $parts;
|
||||
private $controllerPath;
|
||||
|
||||
private $prefix;
|
||||
public function __construct($registry,$prefix='')
|
||||
{
|
||||
$this->registry = $registry;
|
||||
$this->prefix=$prefix;
|
||||
}
|
||||
|
||||
public function loader()
|
||||
{
|
||||
|
||||
try {
|
||||
/*** a new controller class instance , pembuatan controller object***/
|
||||
$class = $this->controller;
|
||||
$this->registry->controller = $class;
|
||||
$this->registry->action = $this->action;
|
||||
$ClassName = ucfirst($class);
|
||||
$mod = strtolower($class);
|
||||
|
||||
$aModules = explode('/', $this->controllerPath);
|
||||
$jumModules = count($aModules);
|
||||
//$mod1 = substr($this->controllerPath, 1);
|
||||
$mod1 = $this->controllerPath;
|
||||
$strslash = substr($this->controllerPath, 0, 1);
|
||||
if ($strslash == '/' || $strslash == '\\') {
|
||||
$mod1 = substr($this->controllerPath, 1);
|
||||
}
|
||||
|
||||
$newmod = str_replace('/', '\\', $mod1);
|
||||
|
||||
$namespaces = "\\modules\\{$newmod}\\controller\\{$ClassName}Controller";
|
||||
|
||||
$this->registry->ContPath = $mod1;
|
||||
|
||||
$controller = new $namespaces($this->registry);
|
||||
|
||||
/*** check if the action is callable ***/
|
||||
if (is_callable(array($controller, $this->action)) == false) {
|
||||
|
||||
$action = 'index';
|
||||
} else {
|
||||
$action = $this->action;
|
||||
}
|
||||
|
||||
/*** run the action , ini sama kayak execute function yang ada pada controller pada mvc sebelumnya
|
||||
* ***/
|
||||
if ($this->registry->config->ajax == 'on') {
|
||||
if (!empty($controller->ActionAjaxOff)) {
|
||||
if (!in_array($action, $controller->ActionAjaxOff)) {
|
||||
// if true
|
||||
|
||||
if (!$this->registry->isAjax) {
|
||||
exit('ajax request required');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!$this->registry->isAjax) {
|
||||
exit('ajax request required');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if ($this->registry->isAjax) {
|
||||
exit('please set ajax config to "on" if request ajax required');
|
||||
}
|
||||
}
|
||||
$controller->$action();
|
||||
} catch (\Exception $e) {
|
||||
$this->registry->log->error('Core / Loader :' . $e->getMessage() . ' Line :' . $e->getLine() . ' ' . $e->getFile());
|
||||
Http::InternalServerError('error loader');
|
||||
}
|
||||
}
|
||||
|
||||
private function getController()
|
||||
{
|
||||
|
||||
try {
|
||||
/* get variable*/
|
||||
$this->controller = $this->getControllerName();
|
||||
$j = 0;
|
||||
if (!(empty($this->parts[2]) or $this->parts[2] == '-')) {
|
||||
for ($i = 2; $i < count($this->parts); $i++) {
|
||||
$this->args[$j] = $this->parts[$i];
|
||||
$j++;
|
||||
}
|
||||
$this->registry->vars = $this->args;
|
||||
} else {
|
||||
$this->registry->vars = 'null';
|
||||
}
|
||||
|
||||
/*** set the file path ***/
|
||||
return $this->controller;
|
||||
} catch (\Exception $e) {
|
||||
|
||||
$this->registry->log->error('Core / Loader :' . $e->getMessage() . ' Line :' . $e->getLine() . ' ' . $e->getFile());
|
||||
\Aiko\Http::InternalServerError('Error loader');
|
||||
}
|
||||
}
|
||||
public function getControllerName()
|
||||
{
|
||||
|
||||
try {
|
||||
$restrict = '';
|
||||
if ($this->registry->config->restrict == 'yes') {
|
||||
if (isset($this->registry->config->ipconfig)) {
|
||||
$ip = $this->getRealIpAddr();
|
||||
$register = in_array($ip, $this->registry->config->ipconfig);
|
||||
|
||||
if ($ip != '127.0.0.1') {
|
||||
if (!$register) {
|
||||
$restrict = 'restrict';
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$restrict = 'restrict';
|
||||
}
|
||||
}
|
||||
$this->getName($restrict);
|
||||
$this->Request_check();
|
||||
|
||||
return $this->controller;
|
||||
} catch (\Exception $e) {
|
||||
|
||||
$this->registry->log->error('Core / Loader :' . $e->getMessage() . ' Line :' . $e->getLine());
|
||||
\Aiko\Http::InternalServerError('Error loader');
|
||||
}
|
||||
}
|
||||
|
||||
private function getName($restrict)
|
||||
{
|
||||
try {
|
||||
if ($restrict == 'restrict') {
|
||||
$this->controller = 'restrict';
|
||||
$this->controllerPath = 'restrict';
|
||||
} else {
|
||||
$route = (empty($_GET['rt'])) ? '' : $_GET['rt'];
|
||||
if (empty($route)) {
|
||||
// jika route tidak ada / pada awal page
|
||||
$route = 'index';
|
||||
} else {
|
||||
// clean root with prefix
|
||||
$route= $this->cleanRoute($route);
|
||||
/*** get the parts of the route ***/
|
||||
$this->parts = explode('/', $route);
|
||||
// set controller name
|
||||
// cek apakan part yang pertama memiliki controller kalau tidak ditemukan return 404
|
||||
if (!is_dir(__SITE_PATH . '/src/modules/' . $this->parts[0])) {
|
||||
$this->controller = 'error404';
|
||||
$this->controllerPath = 'error404';
|
||||
} else {
|
||||
$i = 0;
|
||||
$path = '';
|
||||
$found = false;
|
||||
do {
|
||||
$path .= '/' . $this->parts[$i];
|
||||
$dir = __SITE_PATH . '/src/modules' . $path;
|
||||
if (file_exists($dir . '/controller')) {
|
||||
$found = true;
|
||||
break;
|
||||
}
|
||||
$i++;
|
||||
} while ($i < count($this->parts));
|
||||
if ($found) {
|
||||
$this->controller = $this->parts[$i];
|
||||
$this->controllerPath = $path;
|
||||
} else {
|
||||
$this->controller = 'error404';
|
||||
$this->controllerPath = 'error404';
|
||||
}
|
||||
|
||||
if (isset($this->parts[$i + 1])) {
|
||||
// set action name
|
||||
$this->action = $this->parts[$i + 1];
|
||||
}
|
||||
}
|
||||
}
|
||||
// cek apakah controller kosong, jika kosong set ke index
|
||||
if (empty($this->controller)) {
|
||||
$this->controller = 'index';
|
||||
$this->controllerPath = 'index';
|
||||
}
|
||||
|
||||
/*** Get action ***/
|
||||
if (empty($this->action)) {
|
||||
$this->action = 'index';
|
||||
}
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
|
||||
$this->registry->log->error('Core / Loader :' . $e->getMessage() . ' Line :' . $e->getLine());
|
||||
\Aiko\Http::InternalServerError('Error loader');
|
||||
}
|
||||
}
|
||||
private function Request_check()
|
||||
{
|
||||
$this->registry->isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) and
|
||||
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
|
||||
}
|
||||
public function getControllerPath()
|
||||
{
|
||||
return $this->controllerPath;
|
||||
}
|
||||
private function getRealIpAddr()
|
||||
{
|
||||
if (!empty($_SERVER['HTTP_CLIENT_IP'])) { //check ip from share internet
|
||||
$ip = $_SERVER['HTTP_CLIENT_IP'];
|
||||
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { //to check ip is pass from proxy
|
||||
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
|
||||
} else {
|
||||
$ip = $_SERVER['REMOTE_ADDR'];
|
||||
}
|
||||
return $ip;
|
||||
}
|
||||
|
||||
private function cleanRoute($route):string{
|
||||
$prefixLength=strlen($this->prefix);
|
||||
if ($prefixLength==0){
|
||||
return $route;
|
||||
}
|
||||
$routePrefix=substr($route,0,$prefixLength);
|
||||
if($this->prefix!==$routePrefix){
|
||||
|
||||
Http::InternalServerError('failed route');
|
||||
}
|
||||
$newRoute= substr($route,$prefixLength);
|
||||
if(strlen($newRoute)==0 || $newRoute=='/'){
|
||||
$newRoute='index';
|
||||
}
|
||||
|
||||
// check apakah string pertama route / ?
|
||||
if(substr($newRoute,0,1)=='/'){
|
||||
$newRoute=substr($newRoute,1);
|
||||
}
|
||||
return $newRoute;
|
||||
}
|
||||
|
||||
}
|
0
Aiko/Framework/Core.php:Zone.Identifier
Normal file
0
Aiko/Framework/Core.php:Zone.Identifier
Normal file
3
Aiko/Framework/Core.php:Zone.Identifier:Zone.Identifier
Normal file
3
Aiko/Framework/Core.php:Zone.Identifier:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
184
Aiko/Framework/Database.php
Normal file
184
Aiko/Framework/Database.php
Normal file
@ -0,0 +1,184 @@
|
||||
<?php
|
||||
namespace Aiko\Database;
|
||||
|
||||
include __SITE_PATH . '/Aiko/Includes/db.config.php';
|
||||
|
||||
use PDO;
|
||||
use PDOException;
|
||||
|
||||
|
||||
class Connections
|
||||
{
|
||||
private static $instance = null;
|
||||
private static $instancePMA = NULL;
|
||||
private static $instanceCartal=NULL;
|
||||
private static $scada=NULL;
|
||||
|
||||
private function __construct()
|
||||
{}
|
||||
|
||||
public static function getInstance(
|
||||
$type,
|
||||
$host='127.0.0.1',
|
||||
$socket= '/var/lib/mysql/mysql.sock',
|
||||
$user='root',
|
||||
$password='')
|
||||
{
|
||||
$aHost=array('127.0.0.1','localhost');
|
||||
if(in_array($host,$aHost))
|
||||
{
|
||||
$host = $host;
|
||||
}else {
|
||||
$host='1.1.1.1';
|
||||
}
|
||||
|
||||
$db = $db = 'hcportal_local';
|
||||
$socket = $socket;
|
||||
$user = $user;
|
||||
$pass = $password;
|
||||
if($type!=='local'){
|
||||
$config = getConfig($type);
|
||||
$host = $config['host'];
|
||||
$db = $config['db'];
|
||||
$socket = $config['socket'];
|
||||
$user = $config['user'];
|
||||
$pass = $config['password'];
|
||||
}
|
||||
|
||||
|
||||
if (!self::$instance) {
|
||||
try
|
||||
{
|
||||
switch ($config['dbms']) {
|
||||
case 'mysql':
|
||||
// self::$instance = new PDO("mysql:host=$host;dbname=$db;unix_socket=$socket;port=4867;", "$user","$pass");
|
||||
self::$instance = new PDO("mysql:host=$host;dbname=$db;unix_socket=$socket;", "$user", "$pass");
|
||||
break;
|
||||
case 'oracle':
|
||||
self::$instance = new PDO("oci:host=$host;dbname=$db;", "$user", "$pass");
|
||||
break;
|
||||
case 'pgsql':
|
||||
self::$instance = new PDO("pgsql:host=$host;dbname=$db;", "$user", "$pass");
|
||||
break;
|
||||
case 'sqlite':
|
||||
break;
|
||||
self::$instance = new PDO("sqlite:$db;");
|
||||
|
||||
}
|
||||
self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
self::$instance->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
|
||||
// self::$instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
|
||||
|
||||
return self::$instance;
|
||||
} catch (PDOException $e) {
|
||||
self::showerror("Sorry, an error has occured. Please try your request \n" . $e->getMessage());
|
||||
die();
|
||||
}
|
||||
} else {
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static function getInstancePMA() {
|
||||
$config = getConfig('pma');
|
||||
$host = $config['host'];
|
||||
$db = $config['db'];
|
||||
$socket = $config['socket'];
|
||||
$user = $config['user'];
|
||||
$pass = $config['password'];
|
||||
if (!self::$instancePMA)
|
||||
{
|
||||
try
|
||||
{
|
||||
self::$instancePMA = new PDO("mysql:host=$host;dbname=$db;unix_socket=$socket;", "$user","$pass");
|
||||
self::$instancePMA-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
self::$instancePMA->setAttribute(PDO::ATTR_CASE,PDO::CASE_NATURAL);
|
||||
return self::$instancePMA;
|
||||
}catch (PDOException $e)
|
||||
{
|
||||
self::showerror("Sorry, an error has occured. Please try your request \n".$e->getMessage());
|
||||
die();
|
||||
}
|
||||
}else
|
||||
{
|
||||
return self::$instancePMA;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static function getInstanceCartal($type) {
|
||||
$config = getConfig($type);
|
||||
$host = $config['host'];
|
||||
$db = $config['db'];
|
||||
$socket = $config['socket'];
|
||||
$user = $config['user'];
|
||||
$pass = $config['password'];
|
||||
if (!self::$instanceCartal)
|
||||
{
|
||||
try
|
||||
{
|
||||
self::$instanceCartal = new PDO("mysql:host=$host;dbname=$db;unix_socket=$socket;", "$user","$pass");
|
||||
self::$instanceCartal-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
self::$instanceCartal->setAttribute(PDO::ATTR_CASE,PDO::CASE_NATURAL);
|
||||
return self::$instanceCartal;
|
||||
}catch (PDOException $e)
|
||||
{
|
||||
self::showerror("Sorry, an error has occured. Please try your request \n".$e->getMessage());
|
||||
die();
|
||||
}
|
||||
}else
|
||||
{
|
||||
return self::$instanceCartal;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static function getInstanceSCADA($type) {
|
||||
$config = getConfig($type);
|
||||
$host = $config['host'];
|
||||
$db = $config['db'];
|
||||
$user = $config['user'];
|
||||
$pass = $config['password'];
|
||||
$port = $config['port'];
|
||||
if (!self::$scada)
|
||||
{
|
||||
try
|
||||
{
|
||||
self::$scada = new PDO("pgsql:host=$host;port=$port;dbname=$db;", "$user", "$pass");
|
||||
self::$scada-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
self::$scada->setAttribute(PDO::ATTR_CASE,PDO::CASE_NATURAL);
|
||||
return self::$scada;
|
||||
}catch (PDOException $e)
|
||||
{
|
||||
self::showerror("Sorry, an error has occured. Please try your request \n".$e->getMessage());
|
||||
die();
|
||||
}
|
||||
}else
|
||||
{
|
||||
return self::$instanceCartal;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static function exceptionHandler($e)
|
||||
{
|
||||
set_exception_handler('exceptionHandler');
|
||||
self::showerror("Sorry, the site under maintenance \n");
|
||||
}
|
||||
public static function showerror($m)
|
||||
{
|
||||
echo "<h2>Error</h2>";
|
||||
echo nl2br(htmlspecialchars($m));
|
||||
}
|
||||
/**
|
||||
*
|
||||
*
|
||||
* Like the constructor, we make __clone private
|
||||
* so nobody can clone the instance
|
||||
*
|
||||
*/
|
||||
private function __clone()
|
||||
{}
|
||||
|
||||
}
|
0
Aiko/Framework/Database.php:Zone.Identifier
Normal file
0
Aiko/Framework/Database.php:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
11
Aiko/Framework/Error.php
Normal file
11
Aiko/Framework/Error.php
Normal file
@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
function exception_error_handler($severity, $message, $file, $line)
|
||||
{
|
||||
if (!(error_reporting() & $severity)) {
|
||||
// This error code is not included in error_reporting
|
||||
return;
|
||||
}
|
||||
throw new ErrorException($message, 0, $severity, $file, $line);
|
||||
}
|
||||
set_error_handler('exception_error_handler', E_ALL);
|
0
Aiko/Framework/Error.php:Zone.Identifier
Normal file
0
Aiko/Framework/Error.php:Zone.Identifier
Normal file
3
Aiko/Framework/Error.php:Zone.Identifier:Zone.Identifier
Normal file
3
Aiko/Framework/Error.php:Zone.Identifier:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
126
Aiko/Framework/Init.php
Normal file
126
Aiko/Framework/Init.php
Normal file
@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
|
||||
TODO:
|
||||
- untuk sementara include manual di sini nanti akan di pindahkan ke composer
|
||||
- Second todo item
|
||||
|
||||
*/
|
||||
|
||||
/**setup secret constant */
|
||||
define('__PAYROLLCODE__', '123456');
|
||||
|
||||
define('__CODE_COST', '123456');
|
||||
|
||||
define('__CODE_PKWT_LOA', '123456');
|
||||
|
||||
define('__ENCRYPT_METHOD', 'AES-256-CBC');
|
||||
|
||||
define('__SECRET_KEY', 'suh3ndr441k041l4');
|
||||
|
||||
define('__SECRET_IV', 'suh3ndr441k041l4');
|
||||
|
||||
|
||||
/** include framework files */
|
||||
|
||||
include __SITE_PATH . '/Aiko/Includes/App.config.php';
|
||||
|
||||
include __SITE_PATH . '/Aiko/Framework/Error.php';
|
||||
|
||||
include __SITE_PATH . '/Aiko/Framework/Database.php';
|
||||
|
||||
include __SITE_PATH . '/Aiko/Framework/Model.php';
|
||||
|
||||
include __SITE_PATH . '/Aiko/Framework/Template.php';
|
||||
|
||||
include __SITE_PATH . '/Aiko/Framework/Token.php';
|
||||
|
||||
include __SITE_PATH . '/Aiko/Includes/config.php';
|
||||
|
||||
/** end include framework files */
|
||||
|
||||
|
||||
/*
|
||||
* create object registry
|
||||
*/
|
||||
$registry = new \Aiko\Registry();
|
||||
|
||||
/*
|
||||
* load variable config to registry
|
||||
*/
|
||||
|
||||
|
||||
$registry->config = json_decode(json_encode($config));
|
||||
|
||||
//$registry->config = json_decode(json_encode(parse_ini_file(__SITE_PATH . '/includes/' . 'config.ini')));
|
||||
|
||||
|
||||
// var_dump($registry->config);
|
||||
|
||||
/*
|
||||
* set server address dari file config
|
||||
*/
|
||||
define('__SERVERADDR', $registry->config->server_address);
|
||||
|
||||
/*
|
||||
* set time zone area application
|
||||
*/
|
||||
date_default_timezone_set($registry->config->time_zone);
|
||||
|
||||
/*
|
||||
Create object registry for carry object
|
||||
*/
|
||||
|
||||
$registry->router = new Aiko\Router($registry);
|
||||
|
||||
/*
|
||||
Set Controller Name
|
||||
*/
|
||||
|
||||
$registry->controller = $registry->router->getControllerName();
|
||||
|
||||
/*
|
||||
Create object template
|
||||
*/
|
||||
|
||||
$registry->template = new \Aiko\Template\Template($registry);
|
||||
|
||||
/*
|
||||
Set Debugging
|
||||
*/
|
||||
/*set Aiko Debugging on developer mode*/
|
||||
|
||||
$registry->ab = new \Aiko\Debug($registry->config->environment);
|
||||
|
||||
/* set log aplikasi */
|
||||
$registry->log = new \Aiko\Log($registry->config->log);
|
||||
|
||||
|
||||
//$this->registry = $registry;
|
||||
//$sessionHandler = new \Aiko\Session($registry);
|
||||
// session_set_save_handler($sessionHandler, true);
|
||||
// session_set_save_handler(
|
||||
// array($sessionHandler, 'open'),
|
||||
// array($sessionHandler, 'close'),
|
||||
// array($sessionHandler, 'read'),
|
||||
// array($sessionHandler, 'write'),
|
||||
// array($sessionHandler, 'destroy'),
|
||||
// array($sessionHandler, 'gc')
|
||||
// );
|
||||
// the following prevents unexpected effects when using objects as save handlers
|
||||
// register_shutdown_function('session_write_close');
|
||||
|
||||
// session_start();
|
||||
// proceed to set and retrieve values by key from $_SESSION
|
||||
|
||||
/* turn of dompdf autoload because we use composer */
|
||||
define('DOMPDF_ENABLE_AUTOLOAD', false);
|
||||
|
||||
// require_once __SITE_PATH.'/vendor/dompdf/dompdf/dompdf_config.inc.php';
|
||||
|
||||
/*
|
||||
Run Controller
|
||||
*/
|
||||
|
||||
$registry->router->loader();
|
0
Aiko/Framework/Init.php:Zone.Identifier
Normal file
0
Aiko/Framework/Init.php:Zone.Identifier
Normal file
3
Aiko/Framework/Init.php:Zone.Identifier:Zone.Identifier
Normal file
3
Aiko/Framework/Init.php:Zone.Identifier:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
235
Aiko/Framework/Model.php
Normal file
235
Aiko/Framework/Model.php
Normal file
@ -0,0 +1,235 @@
|
||||
<?php
|
||||
namespace Aiko;
|
||||
|
||||
use Aiko\Database\Connections;
|
||||
use PDO;
|
||||
use PHPExcel;
|
||||
use Exception;
|
||||
|
||||
class Model
|
||||
{
|
||||
use Logdb {
|
||||
insertLog as protected ;
|
||||
}
|
||||
protected $registry;
|
||||
protected $query;
|
||||
protected $param = array();
|
||||
private $stmt;
|
||||
private $db;
|
||||
protected $preparedStatements;
|
||||
public $enabledDebugMode = false;
|
||||
|
||||
public function __construct($registry)
|
||||
{
|
||||
$this->registry = $registry;
|
||||
/* if($this->registry->config->dbMainConType!=='local')
|
||||
{
|
||||
$this->registry->db = Connections::getInstance($this->registry->config->dbMainConType);
|
||||
}else {
|
||||
$this->registry->db = Connections::getInstance(
|
||||
$this->registry->config->dbMainConType,
|
||||
$this->registry->config->host,
|
||||
$this->registry->config->socket,
|
||||
$this->registry->config->user,
|
||||
$this->registry->config->password
|
||||
);
|
||||
} */
|
||||
|
||||
|
||||
}
|
||||
|
||||
public function ConnectToOracle()
|
||||
{
|
||||
try {
|
||||
$host = $this->registry->config->hostOracle;
|
||||
$db = $this->registry->config->dbOracle;
|
||||
$user = $this->registry->config->userOracle;
|
||||
$pass = $this->registry->config->passwordOracle;
|
||||
// die($user.$pass);
|
||||
$this->registry->dbOracle = new PDO("oci:dbname=//$host:1521/$db;", "$user", "$pass", array(
|
||||
PDO::ATTR_TIMEOUT => 10,
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
));
|
||||
$this->registry->dbOracle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
$this->registry->dbOracle->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
|
||||
|
||||
} catch (\PDOException $e) {
|
||||
die("Sorry, an error has occured. Please try your request \n");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public function connectToDBPMA()
|
||||
{
|
||||
$this->registry->dbpma = Connections::getInstancePMA();
|
||||
}
|
||||
|
||||
protected function beginTransaction()
|
||||
{
|
||||
$this->registry->db->beginTransaction();
|
||||
}
|
||||
protected function commit()
|
||||
{
|
||||
$this->registry->db->commit();
|
||||
}
|
||||
protected function rollBack()
|
||||
{
|
||||
$this->registry->db->rollBack();
|
||||
}
|
||||
|
||||
protected function sendResponse($moreInfo, $messages, $status)
|
||||
{
|
||||
return array(
|
||||
"moreInfo" => $moreInfo,
|
||||
"messages" => $messages,
|
||||
"status" => $status,
|
||||
);
|
||||
}
|
||||
|
||||
public function connectToCarTal()
|
||||
{
|
||||
return Connections::getInstanceCartal($this->registry->config->dbCarTalType);
|
||||
}
|
||||
|
||||
public function connectToScada()
|
||||
{
|
||||
return Connections::getInstanceSCADA($this->registry->config->dbScadaType);
|
||||
}
|
||||
|
||||
protected function checkValidNikByEmpId($empId,$nik){
|
||||
try{
|
||||
$stmt=$this->registry->db->prepare('select nik from employement where nik=:nik and emp_profile_id=:emp_id');
|
||||
$stmt->bindValue(':nik',$nik,PDO::PARAM_STR);
|
||||
$stmt->bindValue(':emp_id',$empId,PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
if($stmt->rowCount()>0){
|
||||
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}catch(\PDOException $e){
|
||||
return false;
|
||||
}catch(\ErrorException $e){
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private function serializeColumn($arr = [], $isBinding = false)
|
||||
{
|
||||
$serialize = '';
|
||||
for ($i = 0; $i < count($arr); $i++) {
|
||||
if ($isBinding) {
|
||||
$serialize .= ":$arr[$i],";
|
||||
} else {
|
||||
if (is_numeric($arr[$i])) {
|
||||
$serialize .= "$arr[$i],";
|
||||
} else {
|
||||
$serialize .= "'$arr[$i]',";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return substr($serialize, 0, -1);
|
||||
}
|
||||
|
||||
public function prepareQuery($query)
|
||||
{
|
||||
if (isset($this->preparedStatements[$query])) {
|
||||
$stmt = $this->preparedStatements[$query];
|
||||
} else {
|
||||
// Call PDO::prepare.
|
||||
$stmt = $this->registry->db->prepare($query);
|
||||
$this->preparedStatements[$query] = $stmt;
|
||||
}
|
||||
return $stmt;
|
||||
}
|
||||
|
||||
private function checkDebugMode($stmt)
|
||||
{
|
||||
if ($this->enabledDebugMode) {
|
||||
$stmt->debugDumpParams();
|
||||
die();
|
||||
}
|
||||
}
|
||||
|
||||
protected function error($e, $name="")
|
||||
{
|
||||
if(!empty($name)){
|
||||
$this->registry->log->customError($name, 'Message: '. $e->getMessage() . ' | Line: '. $e->getLine(). ' | File: '. $e->getFile()) . ' | User: ' . \Helper::getSessionVar('username');
|
||||
}else{
|
||||
$this->registry->log->error('Message: '. $e->getMessage() . ' | Line: '. $e->getLine(). ' | File: '. $e->getFile() . ' | User: ' . \Helper::getSessionVar('username'));
|
||||
}
|
||||
}
|
||||
|
||||
protected function getColumnIndex($col)
|
||||
{
|
||||
$idx = \PHPExcel_Cell::columnIndexFromString($col);
|
||||
return $idx - 1;
|
||||
}
|
||||
|
||||
protected function getWorkSheetData($fileName, $sheetIndex)
|
||||
{
|
||||
$objPHPExcel = new PHPExcel();
|
||||
$inputFileType = \PHPExcel_IOFactory::identify($fileName);
|
||||
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
|
||||
|
||||
$objPHPExcel = $objReader->load($fileName);
|
||||
$objWorkSheet = $objPHPExcel->setActiveSheetIndex($sheetIndex);
|
||||
|
||||
return $objWorkSheet;
|
||||
}
|
||||
|
||||
/**
|
||||
* $type allowed
|
||||
* - time untuk jam
|
||||
* - date untuk tanggal
|
||||
*/
|
||||
protected function getColumnValue($objWorkSheet, $columnIndex, $row, $type='')
|
||||
{
|
||||
$result = $objWorkSheet->getCellByColumnAndRow($this->getColumnIndex($columnIndex), $row)->getValue();
|
||||
if(!empty($type)){
|
||||
$format = 'YYYY-MM-DD';
|
||||
$defValue = "1970-01-01";
|
||||
if($type=='time'){
|
||||
$defValue = "00:00:00";
|
||||
$format = 'hh:mm:ss';
|
||||
}
|
||||
if(empty($result)){
|
||||
return $defValue;
|
||||
}
|
||||
return \PHPExcel_Style_NumberFormat::toFormattedString(trim($result), $format);
|
||||
}
|
||||
|
||||
return trim($result);
|
||||
}
|
||||
|
||||
protected function saveFileData($file, $path, $allowedMime = [])
|
||||
{
|
||||
$filename = $file->getClientOriginalName();
|
||||
$mimeType = $file->getClientMimeType();
|
||||
$mimeClientAlowed = array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel');
|
||||
if(count($allowedMime)>0){
|
||||
$mimeClientAlowed = $allowedMime;
|
||||
}
|
||||
if (!in_array($mimeType, $mimeClientAlowed)) {
|
||||
throw new Exception('error file type');
|
||||
}
|
||||
$targetPath = $this->registry->config->base_storage. $path;
|
||||
$targetFile = str_replace('//', '/', $targetPath);
|
||||
$newfilename = $targetFile . '_' . time() . '_' . $filename;
|
||||
// store data to storage
|
||||
$file->move($targetFile, $newfilename);
|
||||
|
||||
return array('filename' => $filename, 'newfilename' => $newfilename);
|
||||
}
|
||||
|
||||
protected function isEmpty($param)
|
||||
{
|
||||
if(is_null($param) || empty($param) || !$param){
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
0
Aiko/Framework/Model.php:Zone.Identifier
Normal file
0
Aiko/Framework/Model.php:Zone.Identifier
Normal file
3
Aiko/Framework/Model.php:Zone.Identifier:Zone.Identifier
Normal file
3
Aiko/Framework/Model.php:Zone.Identifier:Zone.Identifier
Normal file
@ -0,0 +1,3 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=C:\Users\abish\Downloads\Aiko (1).zip
|
107
Aiko/Framework/Template.php
Normal file
107
Aiko/Framework/Template.php
Normal file
@ -0,0 +1,107 @@
|
||||
<?php
|
||||
// class ini berfungsi untuk menentukan view nya yang digunakan
|
||||
namespace Aiko\Template;
|
||||
Class Template {
|
||||
|
||||
private $registry; // variable ini berfungsi untuk menampung object registry
|
||||
|
||||
private $vars = array(); // variable ini berfungsi untuk menyimpan variable variable yang digunakan
|
||||
// oleh templatenya
|
||||
|
||||
|
||||
function __construct($registry) {
|
||||
$this->registry = $registry; // set registry object
|
||||
|
||||
}
|
||||
|
||||
|
||||
public function __set($index, $value) // magic method yang berfungsi untuk set variable untuk template saja
|
||||
{
|
||||
$this->vars[$index] = $value;
|
||||
}
|
||||
|
||||
// ini method yang berfungsi untuk menampilkan view
|
||||
function show($name,$listJS= array(),$listCSS= array()) {
|
||||
// variable path berfungsi menyimpan path file view
|
||||
$path = __SITE_PATH .'/src/modules/'.$this->registry->ContPath. '/views' . '/' . $name . '.php';
|
||||
$pathJS= __SITE_PATH .'/src/modules/'.$this->registry->ContPath. '/js' . '/' . $name . '.js';
|
||||
$srcjs= __SERVERADDR.'/src/modules'.$this->registry->ContPath. '/js' . '/' . $name . '.js';
|
||||
$pathCSS= __SITE_PATH .'/src/modules/'.$this->registry->ContPath. '/css' . '/' . $name . '.css';
|
||||
$srccss= __SERVERADDR.'/src/modules'.$this->registry->ContPath. '/css' . '/' . $name . '.css';
|
||||
if (file_exists($path) == false)
|
||||
{
|
||||
throw new \Exception('Template not found in '. $path);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// Load variables, jadikan index array sebagai variable pada php
|
||||
foreach ($this->vars as $key => $value)
|
||||
{
|
||||
//set variable php
|
||||
$$key = $value;
|
||||
}
|
||||
|
||||
if(sizeof($listCSS)>0)
|
||||
{
|
||||
foreach ($listCSS as $val) {
|
||||
echo "<link href=\"$val\" rel=\"stylesheet\" type=\"text/css\" />";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// include file
|
||||
if (file_exists($pathCSS) == true)
|
||||
{
|
||||
echo "<link href=\"$srccss\" rel=\"stylesheet\" type=\"text/css\" />";
|
||||
}
|
||||
include ($path); // load view
|
||||
if (file_exists($pathJS) == true)
|
||||
{
|
||||
echo "<script type='text/javascript' src='$srcjs'></script>";
|
||||
}
|
||||
if(sizeof($listJS)>0)
|
||||
{
|
||||
foreach ($listJS as $val) {
|
||||
echo "<script type='text/javascript' src='$val'></script>";
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* method ini digunakan untuk menampilkan data dalam PDF
|
||||
* require dompdf
|
||||
*/
|
||||
public function getContentFile($name)
|
||||
{
|
||||
$path = __SITE_PATH .'/src/modules/'.$this->registry->ContPath. '/pdf' . '/' . $name . '.php';
|
||||
|
||||
if (file_exists($path) == false)
|
||||
{
|
||||
throw new \Exception('Template not found in '. $path);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Load variables, jadikan index array sebagai variable pada php
|
||||
foreach ($this->vars as $key => $value)
|
||||
{
|
||||
//set variable php
|
||||
$$key = $value;
|
||||
}
|
||||
|
||||
$obstart=ob_start();
|
||||
if ($obstart == false)
|
||||
{
|
||||
throw new \Exception('output bueffering not start ');
|
||||
return false;
|
||||
}
|
||||
|
||||
include ($path); // load view
|
||||
$out = ob_get_clean();
|
||||
return $out;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
?>
|
0
Aiko/Framework/Template.php:Zone.Identifier
Normal file
0
Aiko/Framework/Template.php:Zone.Identifier
Normal file
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user