Initial commit BIJ CI4

This commit is contained in:
BIJ Dev
2026-04-21 05:49:17 +07:00
commit fa38ac6b24
13170 changed files with 866701 additions and 0 deletions

6
app/.htaccess Normal file
View File

@@ -0,0 +1,6 @@
<IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>

View File

@@ -0,0 +1,399 @@
<?php
declare(strict_types=1);
namespace App\Commands;
use App\Services\Mobile\MobileJsonService;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use Config\Database;
use Throwable;
/**
* Validasi staging: koneksi DB + perilaku MobileJsonService vs ekspektasi CI3.
*
* Opsi:
* --with-uploads Uji upload kecil (save_pp) lalu hapus file & kembalikan photo DB jika perlu
*
* Env opsional (uji mutasi ringan):
* STAGING_VALIDATE_TOKEN token pegawai valid
* STAGING_VALIDATE_PASS password plaintext (untak uji save_password salah)
*/
class ApiStagingValidate extends BaseCommand
{
protected $group = 'Api';
protected $name = 'api:staging-validate';
protected $usage = 'api:staging-validate [--with-uploads]';
protected $description = 'Validasi staging API mobile terhadap DB (parity CI3)';
private int $passed = 0;
private int $failed = 0;
/** @var list<array{endpoint: string, ok: bool, note: string}> */
private array $results = [];
public function run(array $params)
{
$withUploads = CLI::getOption('with-uploads') !== null;
CLI::write('=== API staging validate ===', 'yellow');
CLI::write('Timezone: ' . date_default_timezone_get());
CLI::write('API_PARITY_LOG: ' . (filter_var(env('API_PARITY_LOG', false), FILTER_VALIDATE_BOOLEAN) ? 'true' : 'false'));
if (! $this->databaseReachable()) {
$this->record('database_ping', false, 'Koneksi database gagal — periksa .env (samakan dengan CI3).');
$this->finish($withUploads, false);
return EXIT_ERROR;
}
$this->record('database_ping', true, 'SELECT 1 OK');
$svc = new MobileJsonService();
$db = Database::connect();
$this->assertLoginInvalid($svc);
$this->assertLoginEmpty($svc);
$this->assertLoginWTokenEmpty($svc);
$this->assertLoginWTokenInvalid($svc);
$this->assertProfilInvalid($svc);
$this->assertPresensiTodayInvalid($svc);
$this->assertPresensiInvalid($svc);
$this->assertSaveMasukInvalidToken($svc);
$this->assertSavePulangInvalidToken($svc);
$this->assertSaveIstirahatInvalidToken($svc);
$this->assertSaveAktifitasInvalidToken($svc);
$this->assertSaveCutiInvalidToken($svc);
$this->assertBatalkanCutiInvalidToken($svc);
$this->assertBeritaInvalid($svc);
$this->assertCutiInvalid($svc);
$this->assertLemburInvalid($svc);
$this->assertLiburInvalid($svc);
$this->assertAktifitasInvalid($svc);
$this->assertDaftarTodayInvalid($svc);
$this->assertSavePpInvalidToken($svc);
$this->assertSavePasswordInvalidToken($svc);
$token = $this->fetchSampleToken($db);
if ($token === null) {
$this->record('authenticated_read_tests', true, 'Lewat: tidak ada pegawai dengan token di DB (uji invalid token sudah jalan).');
} else {
$this->runAuthenticatedSuite($svc, $token, $withUploads);
}
$this->assertUploadDirectories();
$allOk = $this->failed === 0;
$this->finish($withUploads, $allOk);
return $allOk ? EXIT_SUCCESS : EXIT_ERROR;
}
private function finish(bool $withUploads, bool $allOk): void
{
$path = WRITEPATH . 'staging' . DIRECTORY_SEPARATOR;
if (! is_dir($path)) {
mkdir($path, 0755, true);
}
$report = [
'generated_at' => date('c'),
'timezone' => date_default_timezone_get(),
'with_uploads' => $withUploads,
'passed' => $this->passed,
'failed' => $this->failed,
'all_ok' => $allOk,
'results' => $this->results,
];
file_put_contents($path . 'last-validation.json', json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
CLI::newLine();
CLI::write("Selesai. Passed: {$this->passed} Failed: {$this->failed}", $allOk ? 'green' : 'red');
CLI::write('Laporan mesin: writable/staging/last-validation.json', 'cyan');
}
private function databaseReachable(): bool
{
try {
Database::connect()->query('SELECT 1');
return true;
} catch (Throwable $e) {
return false;
}
}
private function record(string $endpoint, bool $ok, string $note): void
{
$this->results[] = ['endpoint' => $endpoint, 'ok' => $ok, 'note' => $note];
if ($ok) {
$this->passed++;
CLI::write("[PASS] {$endpoint}: {$note}", 'green');
} else {
$this->failed++;
CLI::write("[FAIL] {$endpoint}: {$note}", 'red');
}
}
private function assertTrue(string $endpoint, bool $cond, string $okMsg, string $failMsg): void
{
$this->record($endpoint, $cond, $cond ? $okMsg : $failMsg);
}
private function assertLoginInvalid(MobileJsonService $svc): void
{
$r = $svc->login('__ci4_staging_nope__', 'wrongpass');
$ok = ($r['status'] === 0 || $r['status'] === '0')
&& ($r['pesan'] ?? '') === 'Username atau Password tidak sesuai'
&& ! array_key_exists('token', $r);
$this->assertTrue('login_invalid', $ok, 'status 0, pesan default, tanpa token', json_encode($r, JSON_UNESCAPED_UNICODE));
}
private function assertLoginEmpty(MobileJsonService $svc): void
{
$r = $svc->login('', '');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ! array_key_exists('token', $r);
$this->assertTrue('login_empty', $ok, 'status 0 tanpa token', json_encode($r, JSON_UNESCAPED_UNICODE));
}
private function assertLoginWTokenEmpty(MobileJsonService $svc): void
{
$r = $svc->loginWToken('');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ($r['pesan'] ?? '') === ''
&& array_key_exists('status', $r) && array_key_exists('pesan', $r) && ! array_key_exists('token', $r);
$this->assertTrue('login_w_token_empty', $ok, 'status 0, pesan kosong, tanpa token', json_encode($r));
}
private function assertLoginWTokenInvalid(MobileJsonService $svc): void
{
$r = $svc->loginWToken('invalid_token_ci4_staging_xyz');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ($r['pesan'] ?? '') === '';
$this->assertTrue('login_w_token_invalid', $ok, 'status 0', json_encode($r));
}
private function assertProfilInvalid(MobileJsonService $svc): void
{
$r = $svc->profil('');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ! array_key_exists('pegawai', $r);
$this->assertTrue('profil_invalid_token', $ok, 'tanpa pegawai', json_encode($r));
}
private function assertPresensiTodayInvalid(MobileJsonService $svc): void
{
$r = $svc->presensiToday('');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ! array_key_exists('data', $r);
$this->assertTrue('presensi_today_invalid', $ok, 'tanpa data', json_encode($r));
}
private function assertPresensiInvalid(MobileJsonService $svc): void
{
$r = $svc->presensi('');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ! array_key_exists('data', $r);
$this->assertTrue('presensi_invalid', $ok, 'tanpa data', json_encode($r));
}
private function assertSaveMasukInvalidToken(MobileJsonService $svc): void
{
$r = $svc->saveMasuk('', 'p.png', '', '0', '0', '0');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ($r['pesan'] ?? '') === 'Tidak ada jadwal kerja';
$this->assertTrue('save_masuk_invalid', $ok, 'pesan jadwal', json_encode($r));
}
private function assertSavePulangInvalidToken(MobileJsonService $svc): void
{
$r = $svc->savePulang('', 'p.png', '', '0', '0', '0');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ($r['pesan'] ?? '') === 'Tidak ada jadwal kerja';
$this->assertTrue('save_pulang_invalid', $ok, 'pesan jadwal', json_encode($r));
}
private function assertSaveIstirahatInvalidToken(MobileJsonService $svc): void
{
$r = $svc->saveIstirahat('', '08:00', '');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ($r['pesan'] ?? '') === 'Tidak ada jadwal kerja';
$this->assertTrue('save_istirahat_invalid', $ok, 'pesan jadwal', json_encode($r));
}
private function assertSaveAktifitasInvalidToken(MobileJsonService $svc): void
{
$r = $svc->saveAktifitas('', 'x.png', '', '2020-01-01', 'd');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ($r['pesan'] ?? '') === '';
$this->assertTrue('save_aktifitas_invalid', $ok, 'status 0 pesan kosong', json_encode($r));
}
private function assertSaveCutiInvalidToken(MobileJsonService $svc): void
{
$r = $svc->saveCuti('', 'x.png', '', '2020-01-01', 'a', 't');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ($r['pesan'] ?? '') === '';
$this->assertTrue('save_cuti_invalid', $ok, 'status 0 pesan kosong', json_encode($r));
}
private function assertBatalkanCutiInvalidToken(MobileJsonService $svc): void
{
$r = $svc->batalkanCuti('', '1');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ($r['pesan'] ?? '') === '';
$this->assertTrue('batalkan_cuti_invalid', $ok, 'status 0', json_encode($r));
}
private function assertBeritaInvalid(MobileJsonService $svc): void
{
$r = $svc->berita('', '0', '5');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ! array_key_exists('data', $r);
$this->assertTrue('berita_invalid', $ok, 'tanpa data', json_encode($r));
}
private function assertCutiInvalid(MobileJsonService $svc): void
{
$r = $svc->cuti('', '0', '5');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ! array_key_exists('data', $r);
$this->assertTrue('cuti_invalid', $ok, 'tanpa data', json_encode($r));
}
private function assertLemburInvalid(MobileJsonService $svc): void
{
$r = $svc->lembur('', '0', '5');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ! array_key_exists('data', $r);
$this->assertTrue('lembur_invalid', $ok, 'tanpa data', json_encode($r));
}
private function assertLiburInvalid(MobileJsonService $svc): void
{
$r = $svc->libur('');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ! array_key_exists('data', $r);
$this->assertTrue('libur_invalid', $ok, 'tanpa data', json_encode($r));
}
private function assertAktifitasInvalid(MobileJsonService $svc): void
{
$r = $svc->aktifitas('', '0', '5');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ! array_key_exists('data', $r);
$this->assertTrue('aktifitas_invalid', $ok, 'tanpa data', json_encode($r));
}
private function assertDaftarTodayInvalid(MobileJsonService $svc): void
{
$r = $svc->daftarToday('');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ! array_key_exists('data', $r);
$this->assertTrue('daftar_today_invalid', $ok, 'tanpa data', json_encode($r));
}
private function assertSavePpInvalidToken(MobileJsonService $svc): void
{
$r = $svc->savePp('', 'x.png', '');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ($r['pesan'] ?? '') === 'Tidak ada jadwal kerja';
$this->assertTrue('save_pp_invalid', $ok, 'pesan sama CI3 untuk token salah', json_encode($r));
}
private function assertSavePasswordInvalidToken(MobileJsonService $svc): void
{
$r = $svc->savePassword('', 'a', 'b');
$ok = ($r['status'] === 0 || $r['status'] === '0') && ($r['pesan'] ?? '') === '-';
$this->assertTrue('save_password_invalid', $ok, 'pesan default -', json_encode($r));
}
private function fetchSampleToken($db): ?string
{
$row = $db->table('pegawai')->select('token')->where('token IS NOT NULL', null, false)->where('token !=', '')->limit(1)->get()->getRow();
return $row && ! empty($row->token) ? (string) $row->token : null;
}
private function runAuthenticatedSuite(MobileJsonService $svc, string $token, bool $withUploads): void
{
$lw = $svc->loginWToken($token);
$ok = ($lw['status'] === 1 || $lw['status'] === '1') && ($lw['pesan'] ?? '') === '' && ! array_key_exists('token', $lw);
$this->assertTrue('login_w_token_valid', $ok, 'status 1, pesan kosong, tanpa token di JSON', json_encode($lw));
$p = $svc->profil($token);
$ok = ($p['status'] === 1 || $p['status'] === '1') && isset($p['pegawai']) && is_object($p['pegawai']);
$this->assertTrue('profil_valid_token', $ok, 'status 1 + pegawai object', json_encode(['status' => $p['status'] ?? null]));
$pt = $svc->presensiToday($token);
$ok = ($pt['status'] === 1 || $pt['status'] === '1') && isset($pt['data']);
$this->assertTrue('presensi_today_valid', $ok, 'status 1 + data', isset($pt['data']) ? 'data ok' : 'no data');
$pr = $svc->presensi($token);
$ok = ! isset($pr['data']) || (isset($pr['data']) && is_array($pr['data']));
$ok = $ok && (($pr['status'] === 0 && ! isset($pr['data'])) || ($pr['status'] === 1 && isset($pr['data'])));
$this->assertTrue('presensi_valid_token', (bool) $ok, 'status sesuai ada/tidak data', json_encode(['status' => $pr['status'] ?? null, 'has_data' => isset($pr['data'])]));
$b = $svc->berita($token, '', '');
$ok = ($b['status'] === 1 || $b['status'] === '1') && isset($b['data']) && is_array($b['data']);
$this->assertTrue('berita_valid', $ok, 'status 1 + data array', json_encode(['count' => isset($b['data']) ? count($b['data']) : -1]));
$c = $svc->cuti($token, '', '');
$ok = ($c['status'] === 1 || $c['status'] === '1') && isset($c['data']) && is_array($c['data']);
$this->assertTrue('cuti_valid', $ok, 'status 1 + data', '');
$l = $svc->lembur($token, '', '');
$ok = ($l['status'] === 1 || $l['status'] === '1') && isset($l['data']) && is_array($l['data']);
$this->assertTrue('lembur_valid', $ok, 'status 1 + data', '');
$lib = $svc->libur($token);
$ok = ($lib['status'] === 1 || $lib['status'] === '1') && isset($lib['data']) && is_array($lib['data']);
$this->assertTrue('libur_valid', $ok, 'status 1 + data', '');
$a = $svc->aktifitas($token, '', '');
$ok = ($a['status'] === 1 || $a['status'] === '1') && isset($a['data']) && is_array($a['data']);
$this->assertTrue('aktifitas_valid', $ok, 'status 1 + data', '');
$d = $svc->daftarToday($token);
$ok = ($d['status'] === 0 && ! isset($d['data'])) || ($d['status'] === 1 && isset($d['data']) && is_array($d['data']));
$this->assertTrue('daftar_today_valid', $ok, 'status konsisten', json_encode(['status' => $d['status'] ?? null]));
// save_istirahat: mulai & selesai kosong — CI4 stabil (tanpa UPDATE)
$ist = $svc->saveIstirahat($token, '', '');
$ok = ($ist['status'] === 0 || $ist['status'] === '0') && ($ist['pesan'] ?? '') === 'Tidak ada jadwal kerja';
$this->assertTrue('save_istirahat_empty_both_ci4', $ok, 'deviasi terdokumen vs CI3 undefined', json_encode($ist));
$envPass = env('STAGING_VALIDATE_PASS', '');
if (is_string($envPass) && $envPass !== '') {
$sp = $svc->savePassword($token, 'definitely_wrong_old_password_xx', 'new');
$ok = ($sp['status'] === 0 || $sp['status'] === '0')
&& str_contains((string) ($sp['pesan'] ?? ''), 'Password lama tidak sesuai');
$this->assertTrue('save_password_wrong_old', $ok, 'pesan salah password lama', json_encode($sp));
}
if ($withUploads) {
$this->runTinyUploadPp($svc, $token);
}
}
private function runTinyUploadPp(MobileJsonService $svc, string $token): void
{
// 1x1 GIF transparan (sangat kecil)
$b64 = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
$db = Database::connect();
$row = $db->table('pegawai')->select('id_pegawai, photo')->where('token', $token)->get()->getRow();
$oldPh = $row->photo ?? '';
$r = $svc->savePp($token, 'staging.gif', $b64);
$dir = FCPATH . 'assets' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'pengguna';
$ok = ($r['status'] === 1 || $r['status'] === '1');
if ($ok && $row) {
$newRow = $db->table('pegawai')->select('photo')->where('id_pegawai', $row->id_pegawai)->get()->getRow();
$fn = $newRow->photo ?? '';
$path = $dir . DIRECTORY_SEPARATOR . $fn;
$ok = $ok && $fn !== '' && is_file($path);
if (is_file($path)) {
@unlink($path);
}
$db->table('pegawai')->where('id_pegawai', $row->id_pegawai)->update(['photo' => $oldPh]);
}
$this->assertTrue('save_pp_upload_roundtrip', $ok, 'upload + file ada + revert photo DB', json_encode($r));
}
private function assertUploadDirectories(): void
{
$subs = ['dokcuti', 'aktifitas', 'absen' . DIRECTORY_SEPARATOR . 'masuk', 'absen' . DIRECTORY_SEPARATOR . 'pulang', 'pengguna'];
$ok = true;
foreach ($subs as $sub) {
$p = FCPATH . 'assets' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $sub;
if (! is_dir($p)) {
mkdir($p, 0755, true);
}
$ok = $ok && is_dir($p) && is_writable($p);
}
$this->assertTrue('upload_directories', $ok, 'folder upload ada & writable', 'cek permission');
}
}

15
app/Common.php Normal file
View File

@@ -0,0 +1,15 @@
<?php
/**
* The goal of this file is to allow developers a location
* where they can overwrite core procedural functions and
* replace them with their own. This file is loaded during
* the bootstrap process and is called during the framework's
* execution.
*
* This can be looked at as a `master helper` file that is
* loaded early on, and may also contain additional functions
* that you'd like to use throughout your entire application
*
* @see: https://codeigniter.com/user_guide/extending/common.html
*/

View File

@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Pemetaan fitur admin CI4 ke grup Ion Auth (nama grup, case-insensitive).
* Selaras `application/modules/admin/config/ci_bootstrap.php` — `page_auth` + useful_links.
*
* Daftar kosong = semua admin yang sudah login (filter authadmin) boleh mengakses.
*
* Grup `supervisor`: akses seperti HRD pada fitur terdaftar, tetapi data dibatasi ke cabang
* (`pegawai.kantor` sama dengan kantor pada baris pegawai pemegang token admin).
*
* Login `admin_auth_source` = `pegawai` (username/password sama aplikasi mobile, tanpa baris
* `admin_users` terhubung lewat `id_pegawai` + grup): hanya fitur di
* {@see self::$pegawaiPanelFeatures}. Bila pegawai punya akun Ion terhubung, login mobile
* memakai sesi `admin_users` + grup (supervisor, HRD, …) seperti login admin biasa.
*/
class AdminAccess extends BaseConfig
{
/**
* Fitur panel web yang boleh untuk login pegawai saja (bukan akun Ion `admin_users`).
*
* @var list<string>
*/
public array $pegawaiPanelFeatures = [
'dashboard',
'apk_link',
];
/**
* Kunci fitur (dipakai `canAccess('...')` dan controller).
*
* @var array<string, list<string>>
*/
public array $features = [
/** Referensi form pegawai (jabatan, unit, dll.) — semua sesi admin panel */
'references' => [],
'dashboard' => [],
'presensi' => [],
/** Management jadwal (master jam kerja) — hanya webmaster & HRD */
'presensi_jadwal' => ['webmaster', 'hrd'],
/** Hari libur perusahaan — hanya webmaster & HRD */
'presensi_libur' => ['webmaster', 'hrd'],
/** Master kantor, unit, jabatan, golongan, berita — hanya webmaster & HRD */
'perusahaan' => ['webmaster', 'hrd'],
/** Tambah pegawai (form create + API create) — hanya webmaster & HRD */
'pegawai_tambah' => ['webmaster', 'hrd'],
'pegawai' => ['webmaster', 'hrd', 'supervisor'],
'cuti' => ['webmaster', 'hrd', 'supervisor'],
'laporan' => ['webmaster', 'hrd', 'supervisor'],
'panel' => ['webmaster'],
'utilitas' => ['webmaster'],
/** Link APK sidebar — sama `useful_links` CI3 */
'apk_link' => [
'webmaster',
'penyelenggara',
'operator_cabang',
'operator_ranting',
'operator_sekolah',
'admin_soal',
'operator_soal',
],
];
}

202
app/Config/App.php Normal file
View File

@@ -0,0 +1,202 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class App extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Base Site URL
* --------------------------------------------------------------------------
*
* URL to your CodeIgniter root. Typically, this will be your base URL,
* WITH a trailing slash:
*
* E.g., http://example.com/
*/
public string $baseURL = 'http://localhost:8080/';
/**
* Allowed Hostnames in the Site URL other than the hostname in the baseURL.
* If you want to accept multiple Hostnames, set this.
*
* E.g.,
* When your site URL ($baseURL) is 'http://example.com/', and your site
* also accepts 'http://media.example.com/' and 'http://accounts.example.com/':
* ['media.example.com', 'accounts.example.com']
*
* @var list<string>
*/
public array $allowedHostnames = [];
/**
* --------------------------------------------------------------------------
* Index File
* --------------------------------------------------------------------------
*
* Typically, this will be your `index.php` file, unless you've renamed it to
* something else. If you have configured your web server to remove this file
* from your site URIs, set this variable to an empty string.
*/
public string $indexPage = 'index.php';
/**
* --------------------------------------------------------------------------
* URI PROTOCOL
* --------------------------------------------------------------------------
*
* This item determines which server global should be used to retrieve the
* URI string. The default setting of 'REQUEST_URI' works for most servers.
* If your links do not seem to work, try one of the other delicious flavors:
*
* 'REQUEST_URI': Uses $_SERVER['REQUEST_URI']
* 'QUERY_STRING': Uses $_SERVER['QUERY_STRING']
* 'PATH_INFO': Uses $_SERVER['PATH_INFO']
*
* WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
public string $uriProtocol = 'REQUEST_URI';
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible.
|
| By default, only these are allowed: `a-z 0-9~%.:_-`
|
| Set an empty string to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be used as: '/\A[<permittedURIChars>]+\z/iu'
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
public string $permittedURIChars = 'a-z 0-9~%.:_\-';
/**
* --------------------------------------------------------------------------
* Default Locale
* --------------------------------------------------------------------------
*
* The Locale roughly represents the language and location that your visitor
* is viewing the site from. It affects the language strings and other
* strings (like currency markers, numbers, etc), that your program
* should run under for this request.
*/
public string $defaultLocale = 'en';
/**
* --------------------------------------------------------------------------
* Negotiate Locale
* --------------------------------------------------------------------------
*
* If true, the current Request object will automatically determine the
* language to use based on the value of the Accept-Language header.
*
* If false, no automatic detection will be performed.
*/
public bool $negotiateLocale = false;
/**
* --------------------------------------------------------------------------
* Supported Locales
* --------------------------------------------------------------------------
*
* If $negotiateLocale is true, this array lists the locales supported
* by the application in descending order of priority. If no match is
* found, the first locale will be used.
*
* IncomingRequest::setLocale() also uses this list.
*
* @var list<string>
*/
public array $supportedLocales = ['en'];
/**
* --------------------------------------------------------------------------
* Application Timezone
* --------------------------------------------------------------------------
*
* The default timezone that will be used in your application to display
* dates with the date helper, and can be retrieved through app_timezone()
*
* @see https://www.php.net/manual/en/timezones.php for list of timezones
* supported by PHP.
*/
public string $appTimezone = 'Asia/Jakarta';
/**
* --------------------------------------------------------------------------
* Default Character Set
* --------------------------------------------------------------------------
*
* This determines which character set is used by default in various methods
* that require a character set to be provided.
*
* @see http://php.net/htmlspecialchars for a list of supported charsets.
*/
public string $charset = 'UTF-8';
/**
* --------------------------------------------------------------------------
* Force Global Secure Requests
* --------------------------------------------------------------------------
*
* If true, this will force every request made to this application to be
* made via a secure connection (HTTPS). If the incoming request is not
* secure, the user will be redirected to a secure version of the page
* and the HTTP Strict Transport Security (HSTS) header will be set.
*/
public bool $forceGlobalSecureRequests = false;
/**
* --------------------------------------------------------------------------
* Reverse Proxy IPs
* --------------------------------------------------------------------------
*
* If your server is behind a reverse proxy, you must whitelist the proxy
* IP addresses from which CodeIgniter should trust headers such as
* X-Forwarded-For or Client-IP in order to properly identify
* the visitor's IP address.
*
* You need to set a proxy IP address or IP address with subnets and
* the HTTP header for the client IP address.
*
* Here are some examples:
* [
* '10.0.1.200' => 'X-Forwarded-For',
* '192.168.5.0/24' => 'X-Real-IP',
* ]
*
* @var array<string, string>
*/
public array $proxyIPs = [];
/**
* --------------------------------------------------------------------------
* Content Security Policy
* --------------------------------------------------------------------------
*
* Enables the Response's Content Secure Policy to restrict the sources that
* can be used for images, scripts, CSS files, audio, video, etc. If enabled,
* the Response object will populate default values for the policy from the
* `ContentSecurityPolicy.php` file. Controllers can always add to those
* restrictions at run time.
*
* For a better understanding of CSP, see these documents:
*
* @see http://www.html5rocks.com/en/tutorials/security/content-security-policy/
* @see http://www.w3.org/TR/CSP/
*/
public bool $CSPEnabled = false;
}

92
app/Config/Autoload.php Normal file
View File

@@ -0,0 +1,92 @@
<?php
namespace Config;
use CodeIgniter\Config\AutoloadConfig;
/**
* -------------------------------------------------------------------
* AUTOLOADER CONFIGURATION
* -------------------------------------------------------------------
*
* This file defines the namespaces and class maps so the Autoloader
* can find the files as needed.
*
* NOTE: If you use an identical key in $psr4 or $classmap, then
* the values in this file will overwrite the framework's values.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*/
class Autoload extends AutoloadConfig
{
/**
* -------------------------------------------------------------------
* Namespaces
* -------------------------------------------------------------------
* This maps the locations of any namespaces in your application to
* their location on the file system. These are used by the autoloader
* to locate files the first time they have been instantiated.
*
* The 'Config' (APPPATH . 'Config') and 'CodeIgniter' (SYSTEMPATH) are
* already mapped for you.
*
* You may change the name of the 'App' namespace if you wish,
* but this should be done prior to creating any namespaced classes,
* else you will need to modify all of those classes for this to work.
*
* @var array<string, list<string>|string>
*/
public $psr4 = [
APP_NAMESPACE => APPPATH,
];
/**
* -------------------------------------------------------------------
* Class Map
* -------------------------------------------------------------------
* The class map provides a map of class names and their exact
* location on the drive. Classes loaded in this manner will have
* slightly faster performance because they will not have to be
* searched for within one or more directories as they would if they
* were being autoloaded through a namespace.
*
* Prototype:
* $classmap = [
* 'MyClass' => '/path/to/class/file.php'
* ];
*
* @var array<string, string>
*/
public $classmap = [];
/**
* -------------------------------------------------------------------
* Files
* -------------------------------------------------------------------
* The files array provides a list of paths to __non-class__ files
* that will be autoloaded. This can be useful for bootstrap operations
* or for loading functions.
*
* Prototype:
* $files = [
* '/path/to/my/file.php',
* ];
*
* @var list<string>
*/
public $files = [];
/**
* -------------------------------------------------------------------
* Helpers
* -------------------------------------------------------------------
* Prototype:
* $helpers = [
* 'form',
* ];
*
* @var list<string>
*/
public $helpers = [];
}

View File

@@ -0,0 +1,34 @@
<?php
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| In development, we want to show as many errors as possible to help
| make sure they don't make it to production. And save us hours of
| painful debugging.
|
| If you set 'display_errors' to '1', CI4's detailed error report will show.
*/
error_reporting(E_ALL);
ini_set('display_errors', '1');
/*
|--------------------------------------------------------------------------
| DEBUG BACKTRACES
|--------------------------------------------------------------------------
| If true, this constant will tell the error screens to display debug
| backtraces along with the other error information. If you would
| prefer to not see this, set this value to false.
*/
defined('SHOW_DEBUG_BACKTRACE') || define('SHOW_DEBUG_BACKTRACE', true);
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. This will control whether Kint is loaded, and a few other
| items. It can always be used within your own application too.
*/
defined('CI_DEBUG') || define('CI_DEBUG', true);

View File

@@ -0,0 +1,25 @@
<?php
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| Don't show ANY in production environments. Instead, let the system catch
| it and display a generic error message.
|
| If you set 'display_errors' to '1', CI4's detailed error report will show.
*/
error_reporting(E_ALL & ~E_DEPRECATED);
// If you want to suppress more types of errors.
// error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
ini_set('display_errors', '0');
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. It's not widely used currently, and may not survive
| release of the framework.
*/
defined('CI_DEBUG') || define('CI_DEBUG', false);

View File

@@ -0,0 +1,38 @@
<?php
/*
* The environment testing is reserved for PHPUnit testing. It has special
* conditions built into the framework at various places to assist with that.
* You cant use it for your development.
*/
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| In development, we want to show as many errors as possible to help
| make sure they don't make it to production. And save us hours of
| painful debugging.
*/
error_reporting(E_ALL);
ini_set('display_errors', '1');
/*
|--------------------------------------------------------------------------
| DEBUG BACKTRACES
|--------------------------------------------------------------------------
| If true, this constant will tell the error screens to display debug
| backtraces along with the other error information. If you would
| prefer to not see this, set this value to false.
*/
defined('SHOW_DEBUG_BACKTRACE') || define('SHOW_DEBUG_BACKTRACE', true);
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. It's not widely used currently, and may not survive
| release of the framework.
*/
defined('CI_DEBUG') || define('CI_DEBUG', true);

View File

@@ -0,0 +1,36 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class CURLRequest extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* CURLRequest Share Connection Options
* --------------------------------------------------------------------------
*
* Share connection options between requests.
*
* @var list<int>
*
* @see https://www.php.net/manual/en/curl.constants.php#constant.curl-lock-data-connect
*/
public array $shareConnectionOptions = [
CURL_LOCK_DATA_CONNECT,
CURL_LOCK_DATA_DNS,
];
/**
* --------------------------------------------------------------------------
* CURLRequest Share Options
* --------------------------------------------------------------------------
*
* Whether share options between requests or not.
*
* If true, all the options won't be reset between requests.
* It may cause an error request with unnecessary headers.
*/
public bool $shareOptions = false;
}

198
app/Config/Cache.php Normal file
View File

@@ -0,0 +1,198 @@
<?php
namespace Config;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\Cache\Handlers\ApcuHandler;
use CodeIgniter\Cache\Handlers\DummyHandler;
use CodeIgniter\Cache\Handlers\FileHandler;
use CodeIgniter\Cache\Handlers\MemcachedHandler;
use CodeIgniter\Cache\Handlers\PredisHandler;
use CodeIgniter\Cache\Handlers\RedisHandler;
use CodeIgniter\Cache\Handlers\WincacheHandler;
use CodeIgniter\Config\BaseConfig;
class Cache extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Primary Handler
* --------------------------------------------------------------------------
*
* The name of the preferred handler that should be used. If for some reason
* it is not available, the $backupHandler will be used in its place.
*/
public string $handler = 'file';
/**
* --------------------------------------------------------------------------
* Backup Handler
* --------------------------------------------------------------------------
*
* The name of the handler that will be used in case the first one is
* unreachable. Often, 'file' is used here since the filesystem is
* always available, though that's not always practical for the app.
*/
public string $backupHandler = 'dummy';
/**
* --------------------------------------------------------------------------
* Key Prefix
* --------------------------------------------------------------------------
*
* This string is added to all cache item names to help avoid collisions
* if you run multiple applications with the same cache engine.
*/
public string $prefix = '';
/**
* --------------------------------------------------------------------------
* Default TTL
* --------------------------------------------------------------------------
*
* The default number of seconds to save items when none is specified.
*
* WARNING: This is not used by framework handlers where 60 seconds is
* hard-coded, but may be useful to projects and modules. This will replace
* the hard-coded value in a future release.
*/
public int $ttl = 60;
/**
* --------------------------------------------------------------------------
* Reserved Characters
* --------------------------------------------------------------------------
*
* A string of reserved characters that will not be allowed in keys or tags.
* Strings that violate this restriction will cause handlers to throw.
* Default: {}()/\@:
*
* NOTE: The default set is required for PSR-6 compliance.
*/
public string $reservedCharacters = '{}()/\@:';
/**
* --------------------------------------------------------------------------
* File settings
* --------------------------------------------------------------------------
*
* Your file storage preferences can be specified below, if you are using
* the File driver.
*
* @var array{storePath?: string, mode?: int}
*/
public array $file = [
'storePath' => WRITEPATH . 'cache/',
'mode' => 0640,
];
/**
* -------------------------------------------------------------------------
* Memcached settings
* -------------------------------------------------------------------------
*
* Your Memcached servers can be specified below, if you are using
* the Memcached drivers.
*
* @see https://codeigniter.com/user_guide/libraries/caching.html#memcached
*
* @var array{host?: string, port?: int, weight?: int, raw?: bool}
*/
public array $memcached = [
'host' => '127.0.0.1',
'port' => 11211,
'weight' => 1,
'raw' => false,
];
/**
* -------------------------------------------------------------------------
* Redis settings
* -------------------------------------------------------------------------
*
* Your Redis server can be specified below, if you are using
* the Redis or Predis drivers.
*
* @var array{
* host?: string,
* password?: string|null,
* port?: int,
* timeout?: int,
* async?: bool,
* persistent?: bool,
* database?: int
* }
*/
public array $redis = [
'host' => '127.0.0.1',
'password' => null,
'port' => 6379,
'timeout' => 0,
'async' => false, // specific to Predis and ignored by the native Redis extension
'persistent' => false,
'database' => 0,
];
/**
* --------------------------------------------------------------------------
* Available Cache Handlers
* --------------------------------------------------------------------------
*
* This is an array of cache engine alias' and class names. Only engines
* that are listed here are allowed to be used.
*
* @var array<string, class-string<CacheInterface>>
*/
public array $validHandlers = [
'apcu' => ApcuHandler::class,
'dummy' => DummyHandler::class,
'file' => FileHandler::class,
'memcached' => MemcachedHandler::class,
'predis' => PredisHandler::class,
'redis' => RedisHandler::class,
'wincache' => WincacheHandler::class,
];
/**
* --------------------------------------------------------------------------
* Web Page Caching: Cache Include Query String
* --------------------------------------------------------------------------
*
* Whether to take the URL query string into consideration when generating
* output cache files. Valid options are:
*
* false = Disabled
* true = Enabled, take all query parameters into account.
* Please be aware that this may result in numerous cache
* files generated for the same page over and over again.
* ['q'] = Enabled, but only take into account the specified list
* of query parameters.
*
* @var bool|list<string>
*/
public $cacheQueryString = false;
/**
* --------------------------------------------------------------------------
* Web Page Caching: Cache Status Codes
* --------------------------------------------------------------------------
*
* HTTP status codes that are allowed to be cached. Only responses with
* these status codes will be cached by the PageCache filter.
*
* Default: [] - Cache all status codes (backward compatible)
*
* Recommended: [200] - Only cache successful responses
*
* You can also use status codes like:
* [200, 404, 410] - Cache successful responses and specific error codes
* [200, 201, 202, 203, 204] - All 2xx successful responses
*
* WARNING: Using [] may cache temporary error pages (404, 500, etc).
* Consider restricting to [200] for production applications to avoid
* caching errors that should be temporary.
*
* @var list<int>
*/
public array $cacheStatusCodes = [];
}

79
app/Config/Constants.php Normal file
View File

@@ -0,0 +1,79 @@
<?php
/*
| --------------------------------------------------------------------
| App Namespace
| --------------------------------------------------------------------
|
| This defines the default Namespace that is used throughout
| CodeIgniter to refer to the Application directory. Change
| this constant to change the namespace that all application
| classes should use.
|
| NOTE: changing this will require manually modifying the
| existing namespaces of App\* namespaced-classes.
*/
defined('APP_NAMESPACE') || define('APP_NAMESPACE', 'App');
/*
| --------------------------------------------------------------------------
| Composer Path
| --------------------------------------------------------------------------
|
| The path that Composer's autoload file is expected to live. By default,
| the vendor folder is in the Root directory, but you can customize that here.
*/
defined('COMPOSER_PATH') || define('COMPOSER_PATH', ROOTPATH . 'vendor/autoload.php');
/*
|--------------------------------------------------------------------------
| Timing Constants
|--------------------------------------------------------------------------
|
| Provide simple ways to work with the myriad of PHP functions that
| require information to be in seconds.
*/
defined('SECOND') || define('SECOND', 1);
defined('MINUTE') || define('MINUTE', 60);
defined('HOUR') || define('HOUR', 3600);
defined('DAY') || define('DAY', 86400);
defined('WEEK') || define('WEEK', 604800);
defined('MONTH') || define('MONTH', 2_592_000);
defined('YEAR') || define('YEAR', 31_536_000);
defined('DECADE') || define('DECADE', 315_360_000);
/*
| --------------------------------------------------------------------------
| Exit Status Codes
| --------------------------------------------------------------------------
|
| Used to indicate the conditions under which the script is exit()ing.
| While there is no universal standard for error codes, there are some
| broad conventions. Three such conventions are mentioned below, for
| those who wish to make use of them. The CodeIgniter defaults were
| chosen for the least overlap with these conventions, while still
| leaving room for others to be defined in future versions and user
| applications.
|
| The three main conventions used for determining exit status codes
| are as follows:
|
| Standard C/C++ Library (stdlibc):
| http://www.gnu.org/software/libc/manual/html_node/Exit-Status.html
| (This link also contains other GNU-specific conventions)
| BSD sysexits.h:
| http://www.gsp.com/cgi-bin/man.cgi?section=3&topic=sysexits
| Bash scripting:
| http://tldp.org/LDP/abs/html/exitcodes.html
|
*/
defined('EXIT_SUCCESS') || define('EXIT_SUCCESS', 0); // no errors
defined('EXIT_ERROR') || define('EXIT_ERROR', 1); // generic error
defined('EXIT_CONFIG') || define('EXIT_CONFIG', 3); // configuration error
defined('EXIT_UNKNOWN_FILE') || define('EXIT_UNKNOWN_FILE', 4); // file not found
defined('EXIT_UNKNOWN_CLASS') || define('EXIT_UNKNOWN_CLASS', 5); // unknown class
defined('EXIT_UNKNOWN_METHOD') || define('EXIT_UNKNOWN_METHOD', 6); // unknown class member
defined('EXIT_USER_INPUT') || define('EXIT_USER_INPUT', 7); // invalid user input
defined('EXIT_DATABASE') || define('EXIT_DATABASE', 8); // database error
defined('EXIT__AUTO_MIN') || define('EXIT__AUTO_MIN', 9); // lowest automatically-assigned error code
defined('EXIT__AUTO_MAX') || define('EXIT__AUTO_MAX', 125); // highest automatically-assigned error code

View File

@@ -0,0 +1,216 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Stores the default settings for the ContentSecurityPolicy, if you
* choose to use it. The values here will be read in and set as defaults
* for the site. If needed, they can be overridden on a page-by-page basis.
*
* Suggested reference for explanations:
*
* @see https://www.html5rocks.com/en/tutorials/security/content-security-policy/
*/
class ContentSecurityPolicy extends BaseConfig
{
// -------------------------------------------------------------------------
// Broadbrush CSP management
// -------------------------------------------------------------------------
/**
* Default CSP report context
*/
public bool $reportOnly = false;
/**
* Specifies a URL where a browser will send reports
* when a content security policy is violated.
*/
public ?string $reportURI = null;
/**
* Specifies a reporting endpoint to which violation reports ought to be sent.
*/
public ?string $reportTo = null;
/**
* Instructs user agents to rewrite URL schemes, changing
* HTTP to HTTPS. This directive is for websites with
* large numbers of old URLs that need to be rewritten.
*/
public bool $upgradeInsecureRequests = false;
// -------------------------------------------------------------------------
// CSP DIRECTIVES SETTINGS
// NOTE: once you set a policy to 'none', it cannot be further restricted
// -------------------------------------------------------------------------
/**
* Will default to `'self'` if not overridden
*
* @var list<string>|string|null
*/
public $defaultSrc;
/**
* Lists allowed scripts' URLs.
*
* @var list<string>|string
*/
public $scriptSrc = 'self';
/**
* Specifies valid sources for JavaScript <script> elements.
*
* @var list<string>|string
*/
public array|string $scriptSrcElem = 'self';
/**
* Specifies valid sources for JavaScript inline event
* handlers and JavaScript URLs.
*
* @var list<string>|string
*/
public array|string $scriptSrcAttr = 'self';
/**
* Lists allowed stylesheets' URLs.
*
* @var list<string>|string
*/
public $styleSrc = 'self';
/**
* Specifies valid sources for stylesheets <link> elements.
*
* @var list<string>|string
*/
public array|string $styleSrcElem = 'self';
/**
* Specifies valid sources for stylesheets inline
* style attributes and `<style>` elements.
*
* @var list<string>|string
*/
public array|string $styleSrcAttr = 'self';
/**
* Defines the origins from which images can be loaded.
*
* @var list<string>|string
*/
public $imageSrc = 'self';
/**
* Restricts the URLs that can appear in a page's `<base>` element.
*
* Will default to self if not overridden
*
* @var list<string>|string|null
*/
public $baseURI;
/**
* Lists the URLs for workers and embedded frame contents
*
* @var list<string>|string
*/
public $childSrc = 'self';
/**
* Limits the origins that you can connect to (via XHR,
* WebSockets, and EventSource).
*
* @var list<string>|string
*/
public $connectSrc = 'self';
/**
* Specifies the origins that can serve web fonts.
*
* @var list<string>|string
*/
public $fontSrc;
/**
* Lists valid endpoints for submission from `<form>` tags.
*
* @var list<string>|string
*/
public $formAction = 'self';
/**
* Specifies the sources that can embed the current page.
* This directive applies to `<frame>`, `<iframe>`, `<embed>`,
* and `<applet>` tags. This directive can't be used in
* `<meta>` tags and applies only to non-HTML resources.
*
* @var list<string>|string|null
*/
public $frameAncestors;
/**
* The frame-src directive restricts the URLs which may
* be loaded into nested browsing contexts.
*
* @var list<string>|string|null
*/
public $frameSrc;
/**
* Restricts the origins allowed to deliver video and audio.
*
* @var list<string>|string|null
*/
public $mediaSrc;
/**
* Allows control over Flash and other plugins.
*
* @var list<string>|string
*/
public $objectSrc = 'self';
/**
* @var list<string>|string|null
*/
public $manifestSrc;
/**
* @var list<string>|string
*/
public array|string $workerSrc = [];
/**
* Limits the kinds of plugins a page may invoke.
*
* @var list<string>|string|null
*/
public $pluginTypes;
/**
* List of actions allowed.
*
* @var list<string>|string|null
*/
public $sandbox;
/**
* Nonce placeholder for style tags.
*/
public string $styleNonceTag = '{csp-style-nonce}';
/**
* Nonce placeholder for script tags.
*/
public string $scriptNonceTag = '{csp-script-nonce}';
/**
* Replace nonce tag automatically?
*/
public bool $autoNonce = true;
}

107
app/Config/Cookie.php Normal file
View File

@@ -0,0 +1,107 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use DateTimeInterface;
class Cookie extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Cookie Prefix
* --------------------------------------------------------------------------
*
* Set a cookie name prefix if you need to avoid collisions.
*/
public string $prefix = '';
/**
* --------------------------------------------------------------------------
* Cookie Expires Timestamp
* --------------------------------------------------------------------------
*
* Default expires timestamp for cookies. Setting this to `0` will mean the
* cookie will not have the `Expires` attribute and will behave as a session
* cookie.
*
* @var DateTimeInterface|int|string
*/
public $expires = 0;
/**
* --------------------------------------------------------------------------
* Cookie Path
* --------------------------------------------------------------------------
*
* Typically will be a forward slash.
*/
public string $path = '/';
/**
* --------------------------------------------------------------------------
* Cookie Domain
* --------------------------------------------------------------------------
*
* Set to `.your-domain.com` for site-wide cookies.
*/
public string $domain = '';
/**
* --------------------------------------------------------------------------
* Cookie Secure
* --------------------------------------------------------------------------
*
* Cookie will only be set if a secure HTTPS connection exists.
*/
public bool $secure = false;
/**
* --------------------------------------------------------------------------
* Cookie HTTPOnly
* --------------------------------------------------------------------------
*
* Cookie will only be accessible via HTTP(S) (no JavaScript).
*/
public bool $httponly = true;
/**
* --------------------------------------------------------------------------
* Cookie SameSite
* --------------------------------------------------------------------------
*
* Configure cookie SameSite setting. Allowed values are:
* - None
* - Lax
* - Strict
* - ''
*
* Alternatively, you can use the constant names:
* - `Cookie::SAMESITE_NONE`
* - `Cookie::SAMESITE_LAX`
* - `Cookie::SAMESITE_STRICT`
*
* Defaults to `Lax` for compatibility with modern browsers. Setting `''`
* (empty string) means default SameSite attribute set by browsers (`Lax`)
* will be set on cookies. If set to `None`, `$secure` must also be set.
*
* @var ''|'Lax'|'None'|'Strict'
*/
public string $samesite = 'Lax';
/**
* --------------------------------------------------------------------------
* Cookie Raw
* --------------------------------------------------------------------------
*
* This flag allows setting a "raw" cookie, i.e., its name and value are
* not URL encoded using `rawurlencode()`.
*
* If this is set to `true`, cookie names should be compliant of RFC 2616's
* list of allowed characters.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes
* @see https://tools.ietf.org/html/rfc2616#section-2.2
*/
public bool $raw = false;
}

105
app/Config/Cors.php Normal file
View File

@@ -0,0 +1,105 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Cross-Origin Resource Sharing (CORS) Configuration
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
*/
class Cors extends BaseConfig
{
/**
* The default CORS configuration.
*
* @var array{
* allowedOrigins: list<string>,
* allowedOriginsPatterns: list<string>,
* supportsCredentials: bool,
* allowedHeaders: list<string>,
* exposedHeaders: list<string>,
* allowedMethods: list<string>,
* maxAge: int,
* }
*/
public array $default = [
/**
* Origins for the `Access-Control-Allow-Origin` header.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
*
* E.g.:
* - ['http://localhost:8080']
* - ['https://www.example.com']
*/
'allowedOrigins' => [],
/**
* Origin regex patterns for the `Access-Control-Allow-Origin` header.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
*
* NOTE: A pattern specified here is part of a regular expression. It will
* be actually `#\A<pattern>\z#`.
*
* E.g.:
* - ['https://\w+\.example\.com']
*/
'allowedOriginsPatterns' => [],
/**
* Weather to send the `Access-Control-Allow-Credentials` header.
*
* The Access-Control-Allow-Credentials response header tells browsers whether
* the server allows cross-origin HTTP requests to include credentials.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
*/
'supportsCredentials' => false,
/**
* Set headers to allow.
*
* The Access-Control-Allow-Headers response header is used in response to
* a preflight request which includes the Access-Control-Request-Headers to
* indicate which HTTP headers can be used during the actual request.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
*/
'allowedHeaders' => [],
/**
* Set headers to expose.
*
* The Access-Control-Expose-Headers response header allows a server to
* indicate which response headers should be made available to scripts running
* in the browser, in response to a cross-origin request.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
*/
'exposedHeaders' => [],
/**
* Set methods to allow.
*
* The Access-Control-Allow-Methods response header specifies one or more
* methods allowed when accessing a resource in response to a preflight
* request.
*
* E.g.:
* - ['GET', 'POST', 'PUT', 'DELETE']
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
*/
'allowedMethods' => [],
/**
* Set how many seconds the results of a preflight request can be cached.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
*/
'maxAge' => 7200,
];
}

204
app/Config/Database.php Normal file
View File

@@ -0,0 +1,204 @@
<?php
namespace Config;
use CodeIgniter\Database\Config;
/**
* Database Configuration
*/
class Database extends Config
{
/**
* The directory that holds the Migrations and Seeds directories.
*/
public string $filesPath = APPPATH . 'Database' . DIRECTORY_SEPARATOR;
/**
* Lets you choose which connection group to use if no other is specified.
*/
public string $defaultGroup = 'default';
/**
* The default database connection.
*
* @var array<string, mixed>
*/
public array $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8mb4',
'DBCollat' => 'utf8mb4_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'numberNative' => false,
'foundRows' => false,
'dateFormat' => [
'date' => 'Y-m-d',
'datetime' => 'Y-m-d H:i:s',
'time' => 'H:i:s',
],
];
// /**
// * Sample database connection for SQLite3.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'database' => 'database.db',
// 'DBDriver' => 'SQLite3',
// 'DBPrefix' => '',
// 'DBDebug' => true,
// 'swapPre' => '',
// 'failover' => [],
// 'foreignKeys' => true,
// 'busyTimeout' => 1000,
// 'synchronous' => null,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for Postgre.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => '',
// 'hostname' => 'localhost',
// 'username' => 'root',
// 'password' => 'root',
// 'database' => 'ci4',
// 'schema' => 'public',
// 'DBDriver' => 'Postgre',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'utf8',
// 'swapPre' => '',
// 'failover' => [],
// 'port' => 5432,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for SQLSRV.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => '',
// 'hostname' => 'localhost',
// 'username' => 'root',
// 'password' => 'root',
// 'database' => 'ci4',
// 'schema' => 'dbo',
// 'DBDriver' => 'SQLSRV',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'utf8',
// 'swapPre' => '',
// 'encrypt' => false,
// 'failover' => [],
// 'port' => 1433,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for OCI8.
// *
// * You may need the following environment variables:
// * NLS_LANG = 'AMERICAN_AMERICA.UTF8'
// * NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// * NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// * NLS_TIMESTAMP_TZ_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => 'localhost:1521/XEPDB1',
// 'username' => 'root',
// 'password' => 'root',
// 'DBDriver' => 'OCI8',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'AL32UTF8',
// 'swapPre' => '',
// 'failover' => [],
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
/**
* This database connection is used when running PHPUnit database tests.
*
* @var array<string, mixed>
*/
public array $tests = [
'DSN' => '',
'hostname' => '127.0.0.1',
'username' => '',
'password' => '',
'database' => ':memory:',
'DBDriver' => 'SQLite3',
'DBPrefix' => 'db_', // Needed to ensure we're working correctly with prefixes live. DO NOT REMOVE FOR CI DEVS
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8',
'DBCollat' => '',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => true,
'failover' => [],
'port' => 3306,
'foreignKeys' => true,
'busyTimeout' => 1000,
'synchronous' => null,
'dateFormat' => [
'date' => 'Y-m-d',
'datetime' => 'Y-m-d H:i:s',
'time' => 'H:i:s',
],
];
public function __construct()
{
parent::__construct();
// Ensure that we always set the database group to 'tests' if
// we are currently running an automated test suite, so that
// we don't overwrite live data on accident.
if (ENVIRONMENT === 'testing') {
$this->defaultGroup = 'tests';
}
}
}

43
app/Config/DocTypes.php Normal file
View File

@@ -0,0 +1,43 @@
<?php
namespace Config;
class DocTypes
{
/**
* List of valid document types.
*
* @var array<string, string>
*/
public array $list = [
'xhtml11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
'xhtml1-strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'xhtml1-trans' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'xhtml1-frame' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'xhtml-basic11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">',
'html5' => '<!DOCTYPE html>',
'html4-strict' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
'html4-trans' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
'html4-frame' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">',
'mathml1' => '<!DOCTYPE math SYSTEM "http://www.w3.org/Math/DTD/mathml1/mathml.dtd">',
'mathml2' => '<!DOCTYPE math PUBLIC "-//W3C//DTD MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/mathml2.dtd">',
'svg10' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">',
'svg11' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">',
'svg11-basic' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Basic//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd">',
'svg11-tiny' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Tiny//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd">',
'xhtml-math-svg-xh' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-math-svg-sh' => '<!DOCTYPE svg:svg PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-rdfa-1' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">',
'xhtml-rdfa-2' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.1//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd">',
];
/**
* Whether to remove the solidus (`/`) character for void HTML elements (e.g. `<input>`)
* for HTML5 compatibility.
*
* Set to:
* `true` - to be HTML5 compatible
* `false` - to be XHTML compatible
*/
public bool $html5 = true;
}

126
app/Config/Email.php Normal file
View File

@@ -0,0 +1,126 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Email extends BaseConfig
{
public string $fromEmail = '';
public string $fromName = '';
public string $recipients = '';
/**
* The "user agent"
*/
public string $userAgent = 'CodeIgniter';
/**
* The mail sending protocol: mail, sendmail, smtp
*/
public string $protocol = 'mail';
/**
* The server path to Sendmail.
*/
public string $mailPath = '/usr/sbin/sendmail';
/**
* SMTP Server Hostname
*/
public string $SMTPHost = '';
/**
* Which SMTP authentication method to use: login, plain
*/
public string $SMTPAuthMethod = 'login';
/**
* SMTP Username
*/
public string $SMTPUser = '';
/**
* SMTP Password
*/
public string $SMTPPass = '';
/**
* SMTP Port
*/
public int $SMTPPort = 25;
/**
* SMTP Timeout (in seconds)
*/
public int $SMTPTimeout = 5;
/**
* Enable persistent SMTP connections
*/
public bool $SMTPKeepAlive = false;
/**
* SMTP Encryption.
*
* @var string '', 'tls' or 'ssl'. 'tls' will issue a STARTTLS command
* to the server. 'ssl' means implicit SSL. Connection on port
* 465 should set this to ''.
*/
public string $SMTPCrypto = 'tls';
/**
* Enable word-wrap
*/
public bool $wordWrap = true;
/**
* Character count to wrap at
*/
public int $wrapChars = 76;
/**
* Type of mail, either 'text' or 'html'
*/
public string $mailType = 'text';
/**
* Character set (utf-8, iso-8859-1, etc.)
*/
public string $charset = 'UTF-8';
/**
* Whether to validate the email address
*/
public bool $validate = false;
/**
* Email Priority. 1 = highest. 5 = lowest. 3 = normal
*/
public int $priority = 3;
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*/
public string $CRLF = "\r\n";
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*/
public string $newline = "\r\n";
/**
* Enable BCC Batch Mode.
*/
public bool $BCCBatchMode = false;
/**
* Number of emails in each BCC batch
*/
public int $BCCBatchSize = 200;
/**
* Enable notify message from server
*/
public bool $DSN = false;
}

109
app/Config/Encryption.php Normal file
View File

@@ -0,0 +1,109 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Encryption configuration.
*
* These are the settings used for encryption, if you don't pass a parameter
* array to the encrypter for creation/initialization.
*/
class Encryption extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Encryption Key Starter
* --------------------------------------------------------------------------
*
* If you use the Encryption class you must set an encryption key (seed).
* You need to ensure it is long enough for the cipher and mode you plan to use.
* See the user guide for more info.
*/
public string $key = '';
/**
* --------------------------------------------------------------------------
* Previous Encryption Keys
* --------------------------------------------------------------------------
*
* When rotating encryption keys, add old keys here to maintain ability
* to decrypt data encrypted with previous keys. Encryption always uses
* the current $key. Decryption tries current key first, then falls back
* to previous keys if decryption fails.
*
* In .env file, use comma-separated string:
* encryption.previousKeys = hex2bin:9be8c64fcea509867...,hex2bin:3f5a1d8e9c2b7a4f6...
*
* @var list<string>|string
*/
public array|string $previousKeys = '';
/**
* --------------------------------------------------------------------------
* Encryption Driver to Use
* --------------------------------------------------------------------------
*
* One of the supported encryption drivers.
*
* Available drivers:
* - OpenSSL
* - Sodium
*/
public string $driver = 'OpenSSL';
/**
* --------------------------------------------------------------------------
* SodiumHandler's Padding Length in Bytes
* --------------------------------------------------------------------------
*
* This is the number of bytes that will be padded to the plaintext message
* before it is encrypted. This value should be greater than zero.
*
* See the user guide for more information on padding.
*/
public int $blockSize = 16;
/**
* --------------------------------------------------------------------------
* Encryption digest
* --------------------------------------------------------------------------
*
* HMAC digest to use, e.g. 'SHA512' or 'SHA256'. Default value is 'SHA512'.
*/
public string $digest = 'SHA512';
/**
* Whether the cipher-text should be raw. If set to false, then it will be base64 encoded.
* This setting is only used by OpenSSLHandler.
*
* Set to false for CI3 Encryption compatibility.
*/
public bool $rawData = true;
/**
* Encryption key info.
* This setting is only used by OpenSSLHandler.
*
* Set to 'encryption' for CI3 Encryption compatibility.
*/
public string $encryptKeyInfo = '';
/**
* Authentication key info.
* This setting is only used by OpenSSLHandler.
*
* Set to 'authentication' for CI3 Encryption compatibility.
*/
public string $authKeyInfo = '';
/**
* Cipher to use.
* This setting is only used by OpenSSLHandler.
*
* Set to 'AES-128-CBC' to decrypt encrypted data that encrypted
* by CI3 Encryption default configuration.
*/
public string $cipher = 'AES-256-CTR';
}

55
app/Config/Events.php Normal file
View File

@@ -0,0 +1,55 @@
<?php
namespace Config;
use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\FrameworkException;
use CodeIgniter\HotReloader\HotReloader;
/*
* --------------------------------------------------------------------
* Application Events
* --------------------------------------------------------------------
* Events allow you to tap into the execution of the program without
* modifying or extending core files. This file provides a central
* location to define your events, though they can always be added
* at run-time, also, if needed.
*
* You create code that can execute by subscribing to events with
* the 'on()' method. This accepts any form of callable, including
* Closures, that will be executed when the event is triggered.
*
* Example:
* Events::on('create', [$myInstance, 'myMethod']);
*/
Events::on('pre_system', static function (): void {
if (ENVIRONMENT !== 'testing') {
if (ini_get('zlib.output_compression')) {
throw FrameworkException::forEnabledZlibOutputCompression();
}
while (ob_get_level() > 0) {
ob_end_flush();
}
ob_start(static fn ($buffer) => $buffer);
}
/*
* --------------------------------------------------------------------
* Debug Toolbar Listeners.
* --------------------------------------------------------------------
* If you delete, they will no longer be collected.
*/
if (CI_DEBUG && ! is_cli()) {
Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect');
service('toolbar')->respond();
// Hot Reload route - for framework use on the hot reloader.
if (ENVIRONMENT === 'development') {
service('routes')->get('__hot-reload', static function (): void {
(new HotReloader())->run();
});
}
}
});

106
app/Config/Exceptions.php Normal file
View File

@@ -0,0 +1,106 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Debug\ExceptionHandler;
use CodeIgniter\Debug\ExceptionHandlerInterface;
use Psr\Log\LogLevel;
use Throwable;
/**
* Setup how the exception handler works.
*/
class Exceptions extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* LOG EXCEPTIONS?
* --------------------------------------------------------------------------
* If true, then exceptions will be logged
* through Services::Log.
*
* Default: true
*/
public bool $log = true;
/**
* --------------------------------------------------------------------------
* DO NOT LOG STATUS CODES
* --------------------------------------------------------------------------
* Any status codes here will NOT be logged if logging is turned on.
* By default, only 404 (Page Not Found) exceptions are ignored.
*
* @var list<int>
*/
public array $ignoreCodes = [404];
/**
* --------------------------------------------------------------------------
* Error Views Path
* --------------------------------------------------------------------------
* This is the path to the directory that contains the 'cli' and 'html'
* directories that hold the views used to generate errors.
*
* Default: APPPATH.'Views/errors'
*/
public string $errorViewPath = APPPATH . 'Views/errors';
/**
* --------------------------------------------------------------------------
* HIDE FROM DEBUG TRACE
* --------------------------------------------------------------------------
* Any data that you would like to hide from the debug trace.
* In order to specify 2 levels, use "/" to separate.
* ex. ['server', 'setup/password', 'secret_token']
*
* @var list<string>
*/
public array $sensitiveDataInTrace = [];
/**
* --------------------------------------------------------------------------
* WHETHER TO THROW AN EXCEPTION ON DEPRECATED ERRORS
* --------------------------------------------------------------------------
* If set to `true`, DEPRECATED errors are only logged and no exceptions are
* thrown. This option also works for user deprecations.
*/
public bool $logDeprecations = true;
/**
* --------------------------------------------------------------------------
* LOG LEVEL THRESHOLD FOR DEPRECATIONS
* --------------------------------------------------------------------------
* If `$logDeprecations` is set to `true`, this sets the log level
* to which the deprecation will be logged. This should be one of the log
* levels recognized by PSR-3.
*
* The related `Config\Logger::$threshold` should be adjusted, if needed,
* to capture logging the deprecations.
*/
public string $deprecationLogLevel = LogLevel::WARNING;
/*
* DEFINE THE HANDLERS USED
* --------------------------------------------------------------------------
* Given the HTTP status code, returns exception handler that
* should be used to deal with this error. By default, it will run CodeIgniter's
* default handler and display the error information in the expected format
* for CLI, HTTP, or AJAX requests, as determined by is_cli() and the expected
* response format.
*
* Custom handlers can be returned if you want to handle one or more specific
* error codes yourself like:
*
* if (in_array($statusCode, [400, 404, 500])) {
* return new \App\Libraries\MyExceptionHandler();
* }
* if ($exception instanceOf PageNotFoundException) {
* return new \App\Libraries\MyExceptionHandler();
* }
*/
public function handler(int $statusCode, Throwable $exception): ExceptionHandlerInterface
{
return new ExceptionHandler($this);
}
}

37
app/Config/Feature.php Normal file
View File

@@ -0,0 +1,37 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Enable/disable backward compatibility breaking features.
*/
class Feature extends BaseConfig
{
/**
* Use improved new auto routing instead of the legacy version.
*/
public bool $autoRoutesImproved = true;
/**
* Use filter execution order in 4.4 or before.
*/
public bool $oldFilterOrder = false;
/**
* The behavior of `limit(0)` in Query Builder.
*
* If true, `limit(0)` returns all records. (the behavior of 4.4.x or before in version 4.x.)
* If false, `limit(0)` returns no records. (the behavior of 3.1.9 or later in version 3.x.)
*/
public bool $limitZeroAsAll = true;
/**
* Use strict location negotiation.
*
* By default, the locale is selected based on a loose comparison of the language code (ISO 639-1)
* Enabling strict comparison will also consider the region code (ISO 3166-1 alpha-2).
*/
public bool $strictLocaleNegotiation = false;
}

112
app/Config/Filters.php Normal file
View File

@@ -0,0 +1,112 @@
<?php
namespace Config;
use App\Filters\AuthAdmin;
use CodeIgniter\Config\Filters as BaseFilters;
use CodeIgniter\Filters\Cors;
use CodeIgniter\Filters\CSRF;
use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\Filters\ForceHTTPS;
use CodeIgniter\Filters\Honeypot;
use CodeIgniter\Filters\InvalidChars;
use CodeIgniter\Filters\PageCache;
use CodeIgniter\Filters\PerformanceMetrics;
use CodeIgniter\Filters\SecureHeaders;
class Filters extends BaseFilters
{
/**
* Configures aliases for Filter classes to
* make reading things nicer and simpler.
*
* @var array<string, class-string|list<class-string>>
*
* [filter_name => classname]
* or [filter_name => [classname1, classname2, ...]]
*/
public array $aliases = [
'authadmin' => AuthAdmin::class,
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'cors' => Cors::class,
'forcehttps' => ForceHTTPS::class,
'pagecache' => PageCache::class,
'performance' => PerformanceMetrics::class,
];
/**
* List of special required filters.
*
* The filters listed here are special. They are applied before and after
* other kinds of filters, and always applied even if a route does not exist.
*
* Filters set by default provide framework functionality. If removed,
* those functions will no longer work.
*
* @see https://codeigniter.com/user_guide/incoming/filters.html#provided-filters
*
* @var array{before: list<string>, after: list<string>}
*/
public array $required = [
'before' => [
'forcehttps', // Force Global Secure Requests
'pagecache', // Web Page Caching
],
'after' => [
'pagecache', // Web Page Caching
'performance', // Performance Metrics
'toolbar', // Debug Toolbar
],
];
/**
* List of filter aliases that are always
* applied before and after every request.
*
* @var array{
* before: array<string, array{except: list<string>|string}>|list<string>,
* after: array<string, array{except: list<string>|string}>|list<string>
* }
*/
public array $globals = [
'before' => [
// 'honeypot',
// 'csrf',
// 'invalidchars',
],
'after' => [
// 'honeypot',
// 'secureheaders',
],
];
/**
* List of filter aliases that works on a
* particular HTTP method (GET, POST, etc.).
*
* Example:
* 'POST' => ['foo', 'bar']
*
* If you use this, you should disable auto-routing because auto-routing
* permits any HTTP method to access a controller. Accessing the controller
* with a method you don't expect could bypass the filter.
*
* @var array<string, list<string>>
*/
public array $methods = [];
/**
* List of filter aliases that should run on any
* before or after URI patterns.
*
* Example:
* 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
*
* @var array<string, array<string, list<string>>>
*/
public array $filters = [];
}

View File

@@ -0,0 +1,12 @@
<?php
namespace Config;
use CodeIgniter\Config\ForeignCharacters as BaseForeignCharacters;
/**
* @immutable
*/
class ForeignCharacters extends BaseForeignCharacters
{
}

73
app/Config/Format.php Normal file
View File

@@ -0,0 +1,73 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Format\JSONFormatter;
use CodeIgniter\Format\XMLFormatter;
class Format extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Available Response Formats
* --------------------------------------------------------------------------
*
* When you perform content negotiation with the request, these are the
* available formats that your application supports. This is currently
* only used with the API\ResponseTrait. A valid Formatter must exist
* for the specified format.
*
* These formats are only checked when the data passed to the respond()
* method is an array.
*
* @var list<string>
*/
public array $supportedResponseFormats = [
'application/json',
'application/xml', // machine-readable XML
'text/xml', // human-readable XML
];
/**
* --------------------------------------------------------------------------
* Formatters
* --------------------------------------------------------------------------
*
* Lists the class to use to format responses with of a particular type.
* For each mime type, list the class that should be used. Formatters
* can be retrieved through the getFormatter() method.
*
* @var array<string, string>
*/
public array $formatters = [
'application/json' => JSONFormatter::class,
'application/xml' => XMLFormatter::class,
'text/xml' => XMLFormatter::class,
];
/**
* --------------------------------------------------------------------------
* Formatters Options
* --------------------------------------------------------------------------
*
* Additional Options to adjust default formatters behaviour.
* For each mime type, list the additional options that should be used.
*
* @var array<string, int>
*/
public array $formatterOptions = [
'application/json' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
'application/xml' => 0,
'text/xml' => 0,
];
/**
* --------------------------------------------------------------------------
* Maximum depth for JSON encoding.
* --------------------------------------------------------------------------
*
* This value determines how deep the JSON encoder will traverse nested structures.
*/
public int $jsonEncodeDepth = 512;
}

44
app/Config/Generators.php Normal file
View File

@@ -0,0 +1,44 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Generators extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Generator Commands' Views
* --------------------------------------------------------------------------
*
* This array defines the mapping of generator commands to the view files
* they are using. If you need to customize them for your own, copy these
* view files in your own folder and indicate the location here.
*
* You will notice that the views have special placeholders enclosed in
* curly braces `{...}`. These placeholders are used internally by the
* generator commands in processing replacements, thus you are warned
* not to delete them or modify the names. If you will do so, you may
* end up disrupting the scaffolding process and throw errors.
*
* YOU HAVE BEEN WARNED!
*
* @var array<string, array<string, string>|string>
*/
public array $views = [
'make:cell' => [
'class' => 'CodeIgniter\Commands\Generators\Views\cell.tpl.php',
'view' => 'CodeIgniter\Commands\Generators\Views\cell_view.tpl.php',
],
'make:command' => 'CodeIgniter\Commands\Generators\Views\command.tpl.php',
'make:config' => 'CodeIgniter\Commands\Generators\Views\config.tpl.php',
'make:controller' => 'CodeIgniter\Commands\Generators\Views\controller.tpl.php',
'make:entity' => 'CodeIgniter\Commands\Generators\Views\entity.tpl.php',
'make:filter' => 'CodeIgniter\Commands\Generators\Views\filter.tpl.php',
'make:migration' => 'CodeIgniter\Commands\Generators\Views\migration.tpl.php',
'make:model' => 'CodeIgniter\Commands\Generators\Views\model.tpl.php',
'make:seeder' => 'CodeIgniter\Commands\Generators\Views\seeder.tpl.php',
'make:validation' => 'CodeIgniter\Commands\Generators\Views\validation.tpl.php',
'session:migration' => 'CodeIgniter\Commands\Generators\Views\migration.tpl.php',
];
}

42
app/Config/Honeypot.php Normal file
View File

@@ -0,0 +1,42 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Honeypot extends BaseConfig
{
/**
* Makes Honeypot visible or not to human
*/
public bool $hidden = true;
/**
* Honeypot Label Content
*/
public string $label = 'Fill This Field';
/**
* Honeypot Field Name
*/
public string $name = 'honeypot';
/**
* Honeypot HTML Template
*/
public string $template = '<label>{label}</label><input type="text" name="{name}" value="">';
/**
* Honeypot container
*
* If you enabled CSP, you can remove `style="display:none"`.
*/
public string $container = '<div style="display:none">{template}</div>';
/**
* The id attribute for Honeypot container tag
*
* Used when CSP is enabled.
*/
public string $containerId = 'hpc';
}

40
app/Config/Hostnames.php Normal file
View File

@@ -0,0 +1,40 @@
<?php
namespace Config;
class Hostnames
{
// List of known two-part TLDs for subdomain extraction
public const TWO_PART_TLDS = [
'co.uk', 'org.uk', 'gov.uk', 'ac.uk', 'sch.uk', 'ltd.uk', 'plc.uk',
'com.au', 'net.au', 'org.au', 'edu.au', 'gov.au', 'asn.au', 'id.au',
'co.jp', 'ac.jp', 'go.jp', 'or.jp', 'ne.jp', 'gr.jp',
'co.nz', 'org.nz', 'govt.nz', 'ac.nz', 'net.nz', 'geek.nz', 'maori.nz', 'school.nz',
'co.in', 'net.in', 'org.in', 'ind.in', 'ac.in', 'gov.in', 'res.in',
'com.cn', 'net.cn', 'org.cn', 'gov.cn', 'edu.cn',
'com.sg', 'net.sg', 'org.sg', 'gov.sg', 'edu.sg', 'per.sg',
'co.za', 'org.za', 'gov.za', 'ac.za', 'net.za',
'co.kr', 'or.kr', 'go.kr', 'ac.kr', 'ne.kr', 'pe.kr',
'co.th', 'or.th', 'go.th', 'ac.th', 'net.th', 'in.th',
'com.my', 'net.my', 'org.my', 'edu.my', 'gov.my', 'mil.my', 'name.my',
'com.mx', 'org.mx', 'net.mx', 'edu.mx', 'gob.mx',
'com.br', 'net.br', 'org.br', 'gov.br', 'edu.br', 'art.br', 'eng.br',
'co.il', 'org.il', 'ac.il', 'gov.il', 'net.il', 'muni.il',
'co.id', 'or.id', 'ac.id', 'go.id', 'net.id', 'web.id', 'my.id',
'com.hk', 'edu.hk', 'gov.hk', 'idv.hk', 'net.hk', 'org.hk',
'com.tw', 'net.tw', 'org.tw', 'edu.tw', 'gov.tw', 'idv.tw',
'com.sa', 'net.sa', 'org.sa', 'gov.sa', 'edu.sa', 'sch.sa', 'med.sa',
'co.ae', 'net.ae', 'org.ae', 'gov.ae', 'ac.ae', 'sch.ae',
'com.tr', 'net.tr', 'org.tr', 'gov.tr', 'edu.tr', 'av.tr', 'gen.tr',
'co.ke', 'or.ke', 'go.ke', 'ac.ke', 'sc.ke', 'me.ke', 'mobi.ke', 'info.ke',
'com.ng', 'org.ng', 'gov.ng', 'edu.ng', 'net.ng', 'sch.ng', 'name.ng',
'com.pk', 'net.pk', 'org.pk', 'gov.pk', 'edu.pk', 'fam.pk',
'com.eg', 'edu.eg', 'gov.eg', 'org.eg', 'net.eg',
'com.cy', 'net.cy', 'org.cy', 'gov.cy', 'ac.cy',
'com.lk', 'org.lk', 'edu.lk', 'gov.lk', 'net.lk', 'int.lk',
'com.bd', 'net.bd', 'org.bd', 'ac.bd', 'gov.bd', 'mil.bd',
'com.ar', 'net.ar', 'org.ar', 'gov.ar', 'edu.ar', 'mil.ar',
'gob.cl', 'com.pl', 'net.pl', 'org.pl', 'gov.pl', 'edu.pl',
'co.ir', 'ac.ir', 'org.ir', 'id.ir', 'gov.ir', 'sch.ir', 'net.ir',
];
}

33
app/Config/Images.php Normal file
View File

@@ -0,0 +1,33 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Images\Handlers\GDHandler;
use CodeIgniter\Images\Handlers\ImageMagickHandler;
class Images extends BaseConfig
{
/**
* Default handler used if no other handler is specified.
*/
public string $defaultHandler = 'gd';
/**
* The path to the image library.
* Required for ImageMagick, GraphicsMagick, or NetPBM.
*
* @deprecated 4.7.0 No longer used.
*/
public string $libraryPath = '/usr/local/bin/convert';
/**
* The available handler classes.
*
* @var array<string, string>
*/
public array $handlers = [
'gd' => GDHandler::class,
'imagick' => ImageMagickHandler::class,
];
}

63
app/Config/Kint.php Normal file
View File

@@ -0,0 +1,63 @@
<?php
namespace Config;
use Kint\Parser\ConstructablePluginInterface;
use Kint\Renderer\Rich\TabPluginInterface;
use Kint\Renderer\Rich\ValuePluginInterface;
/**
* --------------------------------------------------------------------------
* Kint
* --------------------------------------------------------------------------
*
* We use Kint's `RichRenderer` and `CLIRenderer`. This area contains options
* that you can set to customize how Kint works for you.
*
* @see https://kint-php.github.io/kint/ for details on these settings.
*/
class Kint
{
/*
|--------------------------------------------------------------------------
| Global Settings
|--------------------------------------------------------------------------
*/
/**
* @var list<class-string<ConstructablePluginInterface>|ConstructablePluginInterface>|null
*/
public $plugins;
public int $maxDepth = 6;
public bool $displayCalledFrom = true;
public bool $expanded = false;
/*
|--------------------------------------------------------------------------
| RichRenderer Settings
|--------------------------------------------------------------------------
*/
public string $richTheme = 'aante-light.css';
public bool $richFolder = false;
/**
* @var array<string, class-string<ValuePluginInterface>>|null
*/
public $richObjectPlugins;
/**
* @var array<string, class-string<TabPluginInterface>>|null
*/
public $richTabPlugins;
/*
|--------------------------------------------------------------------------
| CLI Settings
|--------------------------------------------------------------------------
*/
public bool $cliColors = true;
public bool $cliForceUTF8 = false;
public bool $cliDetectWidth = true;
public int $cliMinWidth = 40;
}

151
app/Config/Logger.php Normal file
View File

@@ -0,0 +1,151 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Log\Handlers\FileHandler;
use CodeIgniter\Log\Handlers\HandlerInterface;
class Logger extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Error Logging Threshold
* --------------------------------------------------------------------------
*
* You can enable error logging by setting a threshold over zero. The
* threshold determines what gets logged. Any values below or equal to the
* threshold will be logged.
*
* Threshold options are:
*
* - 0 = Disables logging, Error logging TURNED OFF
* - 1 = Emergency Messages - System is unusable
* - 2 = Alert Messages - Action Must Be Taken Immediately
* - 3 = Critical Messages - Application component unavailable, unexpected exception.
* - 4 = Runtime Errors - Don't need immediate action, but should be monitored.
* - 5 = Warnings - Exceptional occurrences that are not errors.
* - 6 = Notices - Normal but significant events.
* - 7 = Info - Interesting events, like user logging in, etc.
* - 8 = Debug - Detailed debug information.
* - 9 = All Messages
*
* You can also pass an array with threshold levels to show individual error types
*
* array(1, 2, 3, 8) = Emergency, Alert, Critical, and Debug messages
*
* For a live site you'll usually enable Critical or higher (3) to be logged otherwise
* your log files will fill up very fast.
*
* @var int|list<int>
*/
public $threshold = (ENVIRONMENT === 'production') ? 4 : 9;
/**
* --------------------------------------------------------------------------
* Date Format for Logs
* --------------------------------------------------------------------------
*
* Each item that is logged has an associated date. You can use PHP date
* codes to set your own date formatting
*/
public string $dateFormat = 'Y-m-d H:i:s';
/**
* --------------------------------------------------------------------------
* Log Handlers
* --------------------------------------------------------------------------
*
* The logging system supports multiple actions to be taken when something
* is logged. This is done by allowing for multiple Handlers, special classes
* designed to write the log to their chosen destinations, whether that is
* a file on the getServer, a cloud-based service, or even taking actions such
* as emailing the dev team.
*
* Each handler is defined by the class name used for that handler, and it
* MUST implement the `CodeIgniter\Log\Handlers\HandlerInterface` interface.
*
* The value of each key is an array of configuration items that are sent
* to the constructor of each handler. The only required configuration item
* is the 'handles' element, which must be an array of integer log levels.
* This is most easily handled by using the constants defined in the
* `Psr\Log\LogLevel` class.
*
* Handlers are executed in the order defined in this array, starting with
* the handler on top and continuing down.
*
* @var array<class-string<HandlerInterface>, array<string, int|list<string>|string>>
*/
public array $handlers = [
/*
* --------------------------------------------------------------------
* File Handler
* --------------------------------------------------------------------
*/
FileHandler::class => [
// The log levels that this handler will handle.
'handles' => [
'critical',
'alert',
'emergency',
'debug',
'error',
'info',
'notice',
'warning',
],
/*
* The default filename extension for log files.
* An extension of 'php' allows for protecting the log files via basic
* scripting, when they are to be stored under a publicly accessible directory.
*
* NOTE: Leaving it blank will default to 'log'.
*/
'fileExtension' => '',
/*
* The file system permissions to be applied on newly created log files.
*
* IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
* integer notation (i.e. 0700, 0644, etc.)
*/
'filePermissions' => 0644,
/*
* Logging Directory Path
*
* By default, logs are written to WRITEPATH . 'logs/'
* Specify a different destination here, if desired.
*/
'path' => '',
],
/*
* The ChromeLoggerHandler requires the use of the Chrome web browser
* and the ChromeLogger extension. Uncomment this block to use it.
*/
// 'CodeIgniter\Log\Handlers\ChromeLoggerHandler' => [
// /*
// * The log levels that this handler will handle.
// */
// 'handles' => ['critical', 'alert', 'emergency', 'debug',
// 'error', 'info', 'notice', 'warning'],
// ],
/*
* The ErrorlogHandler writes the logs to PHP's native `error_log()` function.
* Uncomment this block to use it.
*/
// 'CodeIgniter\Log\Handlers\ErrorlogHandler' => [
// /* The log levels this handler can handle. */
// 'handles' => ['critical', 'alert', 'emergency', 'debug', 'error', 'info', 'notice', 'warning'],
//
// /*
// * The message type where the error should go. Can be 0 or 4, or use the
// * class constants: `ErrorlogHandler::TYPE_OS` (0) or `ErrorlogHandler::TYPE_SAPI` (4)
// */
// 'messageType' => 0,
// ],
];
}

65
app/Config/Migrations.php Normal file
View File

@@ -0,0 +1,65 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Migrations extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Enable/Disable Migrations
* --------------------------------------------------------------------------
*
* Migrations are enabled by default.
*
* You should enable migrations whenever you intend to do a schema migration
* and disable it back when you're done.
*/
public bool $enabled = true;
/**
* --------------------------------------------------------------------------
* Migrations Table
* --------------------------------------------------------------------------
*
* This is the name of the table that will store the current migrations state.
* When migrations runs it will store in a database table which migration
* files have already been run.
*/
public string $table = 'migrations';
/**
* --------------------------------------------------------------------------
* Timestamp Format
* --------------------------------------------------------------------------
*
* This is the format that will be used when creating new migrations
* using the CLI command:
* > php spark make:migration
*
* NOTE: if you set an unsupported format, migration runner will not find
* your migration files.
*
* Supported formats:
* - YmdHis_
* - Y-m-d-His_
* - Y_m_d_His_
*/
public string $timestampFormat = 'Y-m-d-His_';
/**
* --------------------------------------------------------------------------
* Enable/Disable Migration Lock
* --------------------------------------------------------------------------
*
* Locking is disabled by default.
*
* When enabled, it will prevent multiple migration processes
* from running at the same time by using a lock mechanism.
*
* This is useful in production environments to avoid conflicts
* or race conditions during concurrent deployments.
*/
public bool $lock = false;
}

534
app/Config/Mimes.php Normal file
View File

@@ -0,0 +1,534 @@
<?php
namespace Config;
/**
* This file contains an array of mime types. It is used by the
* Upload class to help identify allowed file types.
*
* When more than one variation for an extension exist (like jpg, jpeg, etc)
* the most common one should be first in the array to aid the guess*
* methods. The same applies when more than one mime-type exists for a
* single extension.
*
* When working with mime types, please make sure you have the ´fileinfo´
* extension enabled to reliably detect the media types.
*/
class Mimes
{
/**
* Map of extensions to mime types.
*
* @var array<string, list<string>|string>
*/
public static array $mimes = [
'hqx' => [
'application/mac-binhex40',
'application/mac-binhex',
'application/x-binhex40',
'application/x-mac-binhex40',
],
'cpt' => 'application/mac-compactpro',
'csv' => [
'text/csv',
'text/x-comma-separated-values',
'text/comma-separated-values',
'application/vnd.ms-excel',
'application/x-csv',
'text/x-csv',
'application/csv',
'application/excel',
'application/vnd.msexcel',
'text/plain',
],
'bin' => [
'application/macbinary',
'application/mac-binary',
'application/octet-stream',
'application/x-binary',
'application/x-macbinary',
],
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => [
'application/octet-stream',
'application/vnd.microsoft.portable-executable',
'application/x-dosexec',
'application/x-msdownload',
],
'class' => 'application/octet-stream',
'psd' => [
'application/x-photoshop',
'image/vnd.adobe.photoshop',
],
'so' => 'application/octet-stream',
'sea' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => [
'application/pdf',
'application/force-download',
'application/x-download',
],
'ai' => [
'application/pdf',
'application/postscript',
],
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => [
'application/vnd.ms-excel',
'application/msexcel',
'application/x-msexcel',
'application/x-ms-excel',
'application/x-excel',
'application/x-dos_ms_excel',
'application/xls',
'application/x-xls',
'application/excel',
'application/download',
'application/vnd.ms-office',
'application/msword',
],
'ppt' => [
'application/vnd.ms-powerpoint',
'application/powerpoint',
'application/vnd.ms-office',
'application/msword',
],
'pptx' => [
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
],
'wbxml' => 'application/wbxml',
'wmlc' => 'application/wmlc',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'gtar' => 'application/x-gtar',
'gz' => 'application/x-gzip',
'gzip' => 'application/x-gzip',
'php' => [
'application/x-php',
'application/x-httpd-php',
'application/php',
'text/php',
'text/x-php',
'application/x-httpd-php-source',
],
'php4' => 'application/x-httpd-php',
'php3' => 'application/x-httpd-php',
'phtml' => 'application/x-httpd-php',
'phps' => 'application/x-httpd-php-source',
'js' => [
'application/x-javascript',
'text/plain',
],
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'tar' => 'application/x-tar',
'tgz' => [
'application/x-tar',
'application/x-gzip-compressed',
],
'z' => 'application/x-compress',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => [
'application/x-zip',
'application/zip',
'application/x-zip-compressed',
'application/s-compressed',
'multipart/x-zip',
],
'rar' => [
'application/vnd.rar',
'application/x-rar',
'application/rar',
'application/x-rar-compressed',
],
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => [
'audio/mpeg',
'audio/mpg',
'audio/mpeg3',
'audio/mp3',
],
'aif' => [
'audio/x-aiff',
'audio/aiff',
],
'aiff' => [
'audio/x-aiff',
'audio/aiff',
],
'aifc' => 'audio/x-aiff',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'rv' => 'video/vnd.rn-realvideo',
'wav' => [
'audio/x-wav',
'audio/wave',
'audio/wav',
],
'bmp' => [
'image/bmp',
'image/x-bmp',
'image/x-bitmap',
'image/x-xbitmap',
'image/x-win-bitmap',
'image/x-windows-bmp',
'image/ms-bmp',
'image/x-ms-bmp',
'application/bmp',
'application/x-bmp',
'application/x-win-bitmap',
],
'gif' => 'image/gif',
'jpg' => [
'image/jpeg',
'image/pjpeg',
],
'jpeg' => [
'image/jpeg',
'image/pjpeg',
],
'jpe' => [
'image/jpeg',
'image/pjpeg',
],
'jp2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'j2k' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpf' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpg2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpx' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpm' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'mj2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'mjp2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'png' => [
'image/png',
'image/x-png',
],
'webp' => 'image/webp',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'css' => [
'text/css',
'text/plain',
],
'html' => [
'text/html',
'text/plain',
],
'htm' => [
'text/html',
'text/plain',
],
'shtml' => [
'text/html',
'text/plain',
],
'txt' => 'text/plain',
'text' => 'text/plain',
'log' => [
'text/plain',
'text/x-log',
],
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'xml' => [
'application/xml',
'text/xml',
'text/plain',
],
'xsl' => [
'application/xml',
'text/xsl',
'text/xml',
],
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'avi' => [
'video/x-msvideo',
'video/msvideo',
'video/avi',
'application/x-troff-msvideo',
],
'movie' => 'video/x-sgi-movie',
'doc' => [
'application/msword',
'application/vnd.ms-office',
],
'docx' => [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/zip',
'application/msword',
'application/x-zip',
],
'dot' => [
'application/msword',
'application/vnd.ms-office',
],
'dotx' => [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/zip',
'application/msword',
],
'xlsx' => [
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/zip',
'application/vnd.ms-excel',
'application/msword',
'application/x-zip',
],
'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
'word' => [
'application/msword',
'application/octet-stream',
],
'xl' => 'application/excel',
'eml' => 'message/rfc822',
'json' => [
'application/json',
'text/json',
],
'pem' => [
'application/x-x509-user-cert',
'application/x-pem-file',
'application/octet-stream',
],
'p10' => [
'application/x-pkcs10',
'application/pkcs10',
],
'p12' => 'application/x-pkcs12',
'p7a' => 'application/x-pkcs7-signature',
'p7c' => [
'application/pkcs7-mime',
'application/x-pkcs7-mime',
],
'p7m' => [
'application/pkcs7-mime',
'application/x-pkcs7-mime',
],
'p7r' => 'application/x-pkcs7-certreqresp',
'p7s' => 'application/pkcs7-signature',
'crt' => [
'application/x-x509-ca-cert',
'application/x-x509-user-cert',
'application/pkix-cert',
],
'crl' => [
'application/pkix-crl',
'application/pkcs-crl',
],
'der' => 'application/x-x509-ca-cert',
'kdb' => 'application/octet-stream',
'pgp' => 'application/pgp',
'gpg' => 'application/gpg-keys',
'sst' => 'application/octet-stream',
'csr' => 'application/octet-stream',
'rsa' => 'application/x-pkcs7',
'cer' => [
'application/pkix-cert',
'application/x-x509-ca-cert',
],
'3g2' => 'video/3gpp2',
'3gp' => [
'video/3gp',
'video/3gpp',
],
'mp4' => 'video/mp4',
'm4a' => 'audio/x-m4a',
'f4v' => [
'video/mp4',
'video/x-f4v',
],
'flv' => 'video/x-flv',
'webm' => 'video/webm',
'aac' => 'audio/x-acc',
'm4u' => 'application/vnd.mpegurl',
'm3u' => 'text/plain',
'xspf' => 'application/xspf+xml',
'vlc' => 'application/videolan',
'wmv' => [
'video/x-ms-wmv',
'video/x-ms-asf',
],
'au' => 'audio/x-au',
'ac3' => 'audio/ac3',
'flac' => 'audio/x-flac',
'ogg' => [
'audio/ogg',
'video/ogg',
'application/ogg',
],
'kmz' => [
'application/vnd.google-earth.kmz',
'application/zip',
'application/x-zip',
],
'kml' => [
'application/vnd.google-earth.kml+xml',
'application/xml',
'text/xml',
],
'ics' => 'text/calendar',
'ical' => 'text/calendar',
'zsh' => 'text/x-scriptzsh',
'7zip' => [
'application/x-compressed',
'application/x-zip-compressed',
'application/zip',
'multipart/x-zip',
],
'cdr' => [
'application/cdr',
'application/coreldraw',
'application/x-cdr',
'application/x-coreldraw',
'image/cdr',
'image/x-cdr',
'zz-application/zz-winassoc-cdr',
],
'wma' => [
'audio/x-ms-wma',
'video/x-ms-asf',
],
'jar' => [
'application/java-archive',
'application/x-java-application',
'application/x-jar',
'application/x-compressed',
],
'svg' => [
'image/svg+xml',
'image/svg',
'application/xml',
'text/xml',
],
'vcf' => 'text/x-vcard',
'srt' => [
'text/srt',
'text/plain',
],
'vtt' => [
'text/vtt',
'text/plain',
],
'ico' => [
'image/x-icon',
'image/x-ico',
'image/vnd.microsoft.icon',
],
'stl' => [
'application/sla',
'application/vnd.ms-pki.stl',
'application/x-navistyle',
'model/stl',
'application/octet-stream',
],
];
/**
* Attempts to determine the best mime type for the given file extension.
*
* @return string|null The mime type found, or none if unable to determine.
*/
public static function guessTypeFromExtension(string $extension)
{
$extension = trim(strtolower($extension), '. ');
if (! array_key_exists($extension, static::$mimes)) {
return null;
}
return is_array(static::$mimes[$extension]) ? static::$mimes[$extension][0] : static::$mimes[$extension];
}
/**
* Attempts to determine the best file extension for a given mime type.
*
* @param string|null $proposedExtension - default extension (in case there is more than one with the same mime type)
*
* @return string|null The extension determined, or null if unable to match.
*/
public static function guessExtensionFromType(string $type, ?string $proposedExtension = null)
{
$type = trim(strtolower($type), '. ');
$proposedExtension = trim(strtolower($proposedExtension ?? ''));
if (
$proposedExtension !== ''
&& array_key_exists($proposedExtension, static::$mimes)
&& in_array($type, (array) static::$mimes[$proposedExtension], true)
) {
// The detected mime type matches with the proposed extension.
return $proposedExtension;
}
// Reverse check the mime type list if no extension was proposed.
// This search is order sensitive!
foreach (static::$mimes as $ext => $types) {
if (in_array($type, (array) $types, true)) {
return $ext;
}
}
return null;
}
}

82
app/Config/Modules.php Normal file
View File

@@ -0,0 +1,82 @@
<?php
namespace Config;
use CodeIgniter\Modules\Modules as BaseModules;
/**
* Modules Configuration.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*/
class Modules extends BaseModules
{
/**
* --------------------------------------------------------------------------
* Enable Auto-Discovery?
* --------------------------------------------------------------------------
*
* If true, then auto-discovery will happen across all elements listed in
* $aliases below. If false, no auto-discovery will happen at all,
* giving a slight performance boost.
*
* @var bool
*/
public $enabled = true;
/**
* --------------------------------------------------------------------------
* Enable Auto-Discovery Within Composer Packages?
* --------------------------------------------------------------------------
*
* If true, then auto-discovery will happen across all namespaces loaded
* by Composer, as well as the namespaces configured locally.
*
* @var bool
*/
public $discoverInComposer = true;
/**
* The Composer package list for Auto-Discovery
* This setting is optional.
*
* E.g.:
* [
* 'only' => [
* // List up all packages to auto-discover
* 'codeigniter4/shield',
* ],
* ]
* or
* [
* 'exclude' => [
* // List up packages to exclude.
* 'pestphp/pest',
* ],
* ]
*
* @var array{only?: list<string>, exclude?: list<string>}
*/
public $composerPackages = [];
/**
* --------------------------------------------------------------------------
* Auto-Discovery Rules
* --------------------------------------------------------------------------
*
* Aliases list of all discovery classes that will be active and used during
* the current application request.
*
* If it is not listed, only the base application elements will be used.
*
* @var list<string>
*/
public $aliases = [
'events',
'filters',
'registrars',
'routes',
'services',
];
}

32
app/Config/Optimize.php Normal file
View File

@@ -0,0 +1,32 @@
<?php
namespace Config;
/**
* Optimization Configuration.
*
* NOTE: This class does not extend BaseConfig for performance reasons.
* So you cannot replace the property values with Environment Variables.
*
* WARNING: Do not use these options when running the app in the Worker Mode.
*/
class Optimize
{
/**
* --------------------------------------------------------------------------
* Config Caching
* --------------------------------------------------------------------------
*
* @see https://codeigniter.com/user_guide/concepts/factories.html#config-caching
*/
public bool $configCacheEnabled = false;
/**
* --------------------------------------------------------------------------
* Config Caching
* --------------------------------------------------------------------------
*
* @see https://codeigniter.com/user_guide/concepts/autoloader.html#file-locator-caching
*/
public bool $locatorCacheEnabled = false;
}

37
app/Config/Pager.php Normal file
View File

@@ -0,0 +1,37 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Pager extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Templates
* --------------------------------------------------------------------------
*
* Pagination links are rendered out using views to configure their
* appearance. This array contains aliases and the view names to
* use when rendering the links.
*
* Within each view, the Pager object will be available as $pager,
* and the desired group as $pagerGroup;
*
* @var array<string, string>
*/
public array $templates = [
'default_full' => 'CodeIgniter\Pager\Views\default_full',
'default_simple' => 'CodeIgniter\Pager\Views\default_simple',
'default_head' => 'CodeIgniter\Pager\Views\default_head',
];
/**
* --------------------------------------------------------------------------
* Items Per Page
* --------------------------------------------------------------------------
*
* The default number of results shown in a single page.
*/
public int $perPage = 20;
}

90
app/Config/Paths.php Normal file
View File

@@ -0,0 +1,90 @@
<?php
namespace Config;
/**
* Paths
*
* Holds the paths that are used by the system to
* locate the main directories, app, system, etc.
*
* Modifying these allows you to restructure your application,
* share a system folder between multiple applications, and more.
*
* All paths are relative to the project's root folder.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*/
class Paths
{
/**
* ---------------------------------------------------------------
* SYSTEM FOLDER NAME
* ---------------------------------------------------------------
*
* This must contain the name of your "system" folder. Include
* the path if the folder is not in the same directory as this file.
*/
public string $systemDirectory = __DIR__ . '/../../vendor/codeigniter4/framework/system';
/**
* ---------------------------------------------------------------
* APPLICATION FOLDER NAME
* ---------------------------------------------------------------
*
* If you want this front controller to use a different "app"
* folder than the default one you can set its name here. The folder
* can also be renamed or relocated anywhere on your server. If
* you do, use a full server path.
*
* @see http://codeigniter.com/user_guide/general/managing_apps.html
*/
public string $appDirectory = __DIR__ . '/..';
/**
* ---------------------------------------------------------------
* WRITABLE DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of your "writable" directory.
* The writable directory allows you to group all directories that
* need write permission to a single place that can be tucked away
* for maximum security, keeping it out of the app and/or
* system directories.
*/
public string $writableDirectory = __DIR__ . '/../../writable';
/**
* ---------------------------------------------------------------
* TESTS DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of your "tests" directory.
*/
public string $testsDirectory = __DIR__ . '/../../tests';
/**
* ---------------------------------------------------------------
* VIEW DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of the directory that
* contains the view files used by your application. By
* default this is in `app/Views`. This value
* is used when no value is provided to `Services::renderer()`.
*/
public string $viewDirectory = __DIR__ . '/../Views';
/**
* ---------------------------------------------------------------
* ENVIRONMENT DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of the directory where
* the .env file is located.
* Please consider security implications when changing this
* value - the directory should not be publicly accessible.
*/
public string $envDirectory = __DIR__ . '/../../';
}

28
app/Config/Publisher.php Normal file
View File

@@ -0,0 +1,28 @@
<?php
namespace Config;
use CodeIgniter\Config\Publisher as BasePublisher;
/**
* Publisher Configuration
*
* Defines basic security restrictions for the Publisher class
* to prevent abuse by injecting malicious files into a project.
*/
class Publisher extends BasePublisher
{
/**
* A list of allowed destinations with a (pseudo-)regex
* of allowed files for each destination.
* Attempts to publish to directories not in this list will
* result in a PublisherException. Files that do no fit the
* pattern will cause copy/merge to fail.
*
* @var array<string, string>
*/
public $restrictions = [
ROOTPATH => '*',
FCPATH => '#\.(s?css|js|map|html?|xml|json|webmanifest|ttf|eot|woff2?|gif|jpe?g|tiff?|png|webp|bmp|ico|svg)$#i',
];
}

175
app/Config/Routes.php Normal file
View File

@@ -0,0 +1,175 @@
<?php
use CodeIgniter\Router\RouteCollection;
/**
* @var RouteCollection $routes
*/
$routes->get('/', 'Home::index');
$routes->group('admin', ['namespace' => 'App\Controllers\Admin'], static function ($routes) {
$routes->get('login', 'Auth::login');
$routes->post('login', 'Auth::attempt');
$routes->get('logout', 'Auth::logout');
});
$routes->group('admin', ['namespace' => 'App\Controllers\Admin', 'filter' => 'authadmin'], static function ($routes) {
$routes->get('/', 'Dashboard::index');
$routes->get('pegawai', 'Pegawai::index');
$routes->get('pegawai/create', 'Pegawai::create');
$routes->post('pegawai/store', 'Pegawai::store');
$routes->get('pegawai/edit/(:num)', 'Pegawai::edit/$1');
$routes->post('pegawai/update/(:num)', 'Pegawai::update/$1');
$routes->post('pegawai/delete/(:num)', 'Pegawai::delete/$1');
$routes->post('pegawai/reset/(:num)', 'Pegawai::reset/$1');
$routes->get('presensi', 'Presensi::index');
$routes->get('presensi/export', 'Presensi::exportCsv');
$routes->get('presensi/export-xlsx', 'Presensi::exportXlsx');
$routes->get('presensi/foto/(:segment)/(:segment)', 'Presensi::foto/$1/$2');
$routes->get('presensi/detail/(:num)', 'Presensi::detail/$1');
$routes->get('laporan', 'Laporan::index');
$routes->get('laporan/cuti', 'Laporan::cuti');
$routes->get('perusahaan/kantor', 'Company::kantor');
$routes->get('perusahaan/unit_kerja', 'Company::unitKerja');
$routes->get('perusahaan/golongan', 'Company::golongan');
$routes->get('perusahaan/jabatan', 'Company::jabatan');
$routes->get('perusahaan/berita', 'Company::berita');
$routes->post('perusahaan/kantor/save', 'Company::kantorSave');
$routes->post('perusahaan/kantor/delete/(:num)', 'Company::kantorDelete/$1');
$routes->post('perusahaan/unit_kerja/save', 'Company::unitKerjaSave');
$routes->post('perusahaan/unit_kerja/delete/(:num)', 'Company::unitKerjaDelete/$1');
$routes->post('perusahaan/golongan/save', 'Company::golonganSave');
$routes->post('perusahaan/golongan/delete/(:num)', 'Company::golonganDelete/$1');
$routes->post('perusahaan/jabatan/save', 'Company::jabatanSave');
$routes->post('perusahaan/jabatan/delete/(:num)', 'Company::jabatanDelete/$1');
$routes->post('perusahaan/berita/save', 'Company::beritaSave');
$routes->post('perusahaan/berita/delete/(:num)', 'Company::beritaDelete/$1');
$routes->get('presensi/lapangan', 'Presensi::lapangan');
$routes->get('presensi/lembur', 'Presensi::lembur');
$routes->get('presensi/libur', 'Presensi::libur');
$routes->get('presensi/jadwal', 'Presensi::jadwal');
$routes->get('presensi/aktivitas', 'Presensi::aktivitas');
$routes->post('presensi/lapangan/save', 'Presensi::lapanganSave');
$routes->post('presensi/lapangan/delete/(:num)', 'Presensi::lapanganDelete/$1');
$routes->post('presensi/lembur/save', 'Presensi::lemburSave');
$routes->post('presensi/lembur/delete/(:num)', 'Presensi::lemburDelete/$1');
$routes->post('presensi/libur/save', 'Presensi::liburSave');
$routes->post('presensi/libur/delete/(:num)', 'Presensi::liburDelete/$1');
$routes->post('presensi/jadwal/save', 'Presensi::jadwalSave');
$routes->post('presensi/jadwal/delete/(:num)', 'Presensi::jadwalDelete/$1');
$routes->post('presensi/aktivitas/delete/(:num)', 'Presensi::aktivitasDelete/$1');
$routes->get('panel/users', 'Panel::users');
$routes->get('panel/groups', 'Panel::groups');
$routes->get('panel/groups/create', 'Panel::groupCreate');
$routes->post('panel/groups/store', 'Panel::groupStore');
$routes->get('panel/groups/edit/(:num)', 'Panel::groupEdit/$1');
$routes->post('panel/groups/update/(:num)', 'Panel::groupUpdate/$1');
$routes->post('panel/groups/delete/(:num)', 'Panel::groupDelete/$1');
$routes->get('panel/users/create', 'Panel::userCreate');
$routes->post('panel/users/store', 'Panel::userStore');
$routes->get('panel/users/edit/(:num)', 'Panel::userEdit/$1');
$routes->post('panel/users/update/(:num)', 'Panel::userUpdate/$1');
$routes->get('panel/users/reset/(:num)', 'Panel::userReset/$1');
$routes->post('panel/users/reset_password/(:num)', 'Panel::userResetPassword/$1');
$routes->get('util/backup', 'Util::backup');
$routes->post('util/backup/run', 'Util::backupRun');
$routes->post('util/backup/delete/(:segment)', 'Util::backupDelete/$1');
$routes->get('util/backup/download/(:segment)', 'Util::backupDownload/$1');
$routes->get('cuti', 'Cuti::index');
$routes->get('cuti/dokumen/(:segment)', 'Cuti::dokumen/$1');
$routes->get('cuti/detail/(:num)', 'Cuti::detail/$1');
$routes->post('cuti/approve/(:num)', 'Cuti::approve/$1');
$routes->post('cuti/reject/(:num)', 'Cuti::reject/$1');
});
$routes->group('api/admin', ['namespace' => 'App\Controllers\Api\Admin'], static function ($routes) {
$routes->get('references', 'ReferenceController::index');
$routes->get('dashboard', 'DashboardController::index');
$routes->get('pegawai', 'PegawaiController::index');
$routes->get('pegawai/(:num)', 'PegawaiController::show/$1');
$routes->post('pegawai/create', 'PegawaiController::create');
$routes->post('pegawai/update', 'PegawaiController::update');
$routes->post('pegawai/delete', 'PegawaiController::delete');
$routes->post('pegawai/reset_password', 'PegawaiController::resetPassword');
$routes->get('presensi', 'PresensiController::index');
$routes->get('presensi/(:num)', 'PresensiController::show/$1');
$routes->get('laporan', 'LaporanController::index');
$routes->get('cuti', 'CutiController::index');
$routes->get('cuti/(:num)', 'CutiController::show/$1');
$routes->post('cuti/approve', 'CutiController::approve');
$routes->post('cuti/reject', 'CutiController::reject');
$routes->get('laporan/cuti', 'LaporanController::cutiRentang');
$routes->get('company/kantor', 'CompanyDataApiController::kantor');
$routes->post('company/kantor/save', 'CompanyDataApiController::kantorSave');
$routes->post('company/kantor/delete/(:num)', 'CompanyDataApiController::kantorDelete/$1');
$routes->get('company/unit_kerja', 'CompanyDataApiController::unitKerja');
$routes->post('company/unit_kerja/save', 'CompanyDataApiController::unitKerjaSave');
$routes->post('company/unit_kerja/delete/(:num)', 'CompanyDataApiController::unitKerjaDelete/$1');
$routes->get('company/golongan', 'CompanyDataApiController::golongan');
$routes->post('company/golongan/save', 'CompanyDataApiController::golonganSave');
$routes->post('company/golongan/delete/(:num)', 'CompanyDataApiController::golonganDelete/$1');
$routes->get('company/jabatan', 'CompanyDataApiController::jabatan');
$routes->post('company/jabatan/save', 'CompanyDataApiController::jabatanSave');
$routes->post('company/jabatan/delete/(:num)', 'CompanyDataApiController::jabatanDelete/$1');
$routes->get('company/berita', 'CompanyDataApiController::berita');
$routes->post('company/berita/save', 'CompanyDataApiController::beritaSave');
$routes->post('company/berita/delete/(:num)', 'CompanyDataApiController::beritaDelete/$1');
$routes->get('presensi/dilapangan', 'PresensiToolsApiController::dilapangan');
$routes->post('presensi/dilapangan/save', 'PresensiToolsApiController::dilapanganSave');
$routes->post('presensi/dilapangan/delete/(:num)', 'PresensiToolsApiController::dilapanganDelete/$1');
$routes->get('presensi/lembur', 'PresensiToolsApiController::lembur');
$routes->post('presensi/lembur/save', 'PresensiToolsApiController::lemburSave');
$routes->post('presensi/lembur/delete/(:num)', 'PresensiToolsApiController::lemburDelete/$1');
$routes->get('presensi/libur', 'PresensiToolsApiController::libur');
$routes->post('presensi/libur/save', 'PresensiToolsApiController::liburSave');
$routes->post('presensi/libur/delete/(:num)', 'PresensiToolsApiController::liburDelete/$1');
$routes->get('presensi/jadwal', 'PresensiToolsApiController::jadwal');
$routes->post('presensi/jadwal/save', 'PresensiToolsApiController::jadwalSave');
$routes->post('presensi/jadwal/delete/(:num)', 'PresensiToolsApiController::jadwalDelete/$1');
$routes->get('presensi/aktivitas', 'PresensiToolsApiController::aktivitas');
$routes->post('presensi/aktivitas/delete/(:num)', 'PresensiToolsApiController::aktivitasDelete/$1');
$routes->get('panel/users', 'PanelUsersApiController::users');
$routes->get('panel/groups', 'PanelUsersApiController::groups');
$routes->post('panel/groups/create', 'PanelUsersApiController::groupCreate');
$routes->post('panel/groups/update/(:num)', 'PanelUsersApiController::groupUpdate/$1');
$routes->post('panel/groups/delete/(:num)', 'PanelUsersApiController::groupDelete/$1');
$routes->get('panel/users/(:num)', 'PanelUsersApiController::userShow/$1');
$routes->post('panel/users/create', 'PanelUsersApiController::userCreate');
$routes->post('panel/users/update/(:num)', 'PanelUsersApiController::userUpdate/$1');
$routes->post('panel/users/reset_password/(:num)', 'PanelUsersApiController::userResetPassword/$1');
$routes->get('backup', 'DatabaseBackupApiController::index');
$routes->post('backup/run', 'DatabaseBackupApiController::run');
$routes->post('backup/delete/(:segment)', 'DatabaseBackupApiController::delete/$1');
});
/*
* --------------------------------------------------------------------
* API mobile (port CI3 application/controllers/Json.php)
* --------------------------------------------------------------------
* Rute utama: /api/mobile/{method}
* Alias kompatibilitas path CI3: /json/{method} (POST)
*/
$mobileJsonRoutes = static function ($routes): void {
$routes->post('login_w_token', 'MobileJsonController::login_w_token');
$routes->post('login', 'MobileJsonController::login');
$routes->post('profil', 'MobileJsonController::profil');
$routes->post('save_cuti', 'MobileJsonController::save_cuti');
$routes->post('batalkan_cuti', 'MobileJsonController::batalkan_cuti');
$routes->post('save_aktifitas', 'MobileJsonController::save_aktifitas');
$routes->post('save_masuk', 'MobileJsonController::save_masuk');
$routes->post('save_pulang', 'MobileJsonController::save_pulang');
$routes->post('save_istirahat', 'MobileJsonController::save_istirahat');
$routes->post('presensi_today', 'MobileJsonController::presensi_today');
$routes->post('presensi', 'MobileJsonController::presensi');
$routes->post('daftar_today', 'MobileJsonController::daftar_today');
$routes->post('berita', 'MobileJsonController::berita');
$routes->post('cuti', 'MobileJsonController::cuti');
$routes->post('lembur', 'MobileJsonController::lembur');
$routes->post('libur', 'MobileJsonController::libur');
$routes->post('aktifitas', 'MobileJsonController::aktifitas');
$routes->post('save_pp', 'MobileJsonController::save_pp');
$routes->post('save_password', 'MobileJsonController::save_password');
};
$routes->group('api/mobile', ['namespace' => 'App\Controllers\Api'], $mobileJsonRoutes);
$routes->group('json', ['namespace' => 'App\Controllers\Api'], $mobileJsonRoutes);

149
app/Config/Routing.php Normal file
View File

@@ -0,0 +1,149 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Config;
use CodeIgniter\Config\Routing as BaseRouting;
/**
* Routing configuration
*/
class Routing extends BaseRouting
{
/**
* For Defined Routes.
* An array of files that contain route definitions.
* Route files are read in order, with the first match
* found taking precedence.
*
* Default: APPPATH . 'Config/Routes.php'
*
* @var list<string>
*/
public array $routeFiles = [
APPPATH . 'Config/Routes.php',
];
/**
* For Defined Routes and Auto Routing.
* The default namespace to use for Controllers when no other
* namespace has been specified.
*
* Default: 'App\Controllers'
*/
public string $defaultNamespace = 'App\Controllers';
/**
* For Auto Routing.
* The default controller to use when no other controller has been
* specified.
*
* Default: 'Home'
*/
public string $defaultController = 'Home';
/**
* For Defined Routes and Auto Routing.
* The default method to call on the controller when no other
* method has been set in the route.
*
* Default: 'index'
*/
public string $defaultMethod = 'index';
/**
* For Auto Routing.
* Whether to translate dashes in URIs for controller/method to underscores.
* Primarily useful when using the auto-routing.
*
* Default: false
*/
public bool $translateURIDashes = false;
/**
* Sets the class/method that should be called if routing doesn't
* find a match. It can be the controller/method name like: Users::index
*
* This setting is passed to the Router class and handled there.
*
* If you want to use a closure, you will have to set it in the
* routes file by calling:
*
* $routes->set404Override(function() {
* // Do something here
* });
*
* Example:
* public $override404 = 'App\Errors::show404';
*/
public ?string $override404 = null;
/**
* If TRUE, the system will attempt to match the URI against
* Controllers by matching each segment against folders/files
* in APPPATH/Controllers, when a match wasn't found against
* defined routes.
*
* If FALSE, will stop searching and do NO automatic routing.
*/
public bool $autoRoute = false;
/**
* If TRUE, the system will look for attributes on controller
* class and methods that can run before and after the
* controller/method.
*
* If FALSE, will ignore any attributes.
*/
public bool $useControllerAttributes = true;
/**
* For Defined Routes.
* If TRUE, will enable the use of the 'prioritize' option
* when defining routes.
*
* Default: false
*/
public bool $prioritize = false;
/**
* For Defined Routes.
* If TRUE, matched multiple URI segments will be passed as one parameter.
*
* Default: false
*/
public bool $multipleSegmentsOneParam = false;
/**
* For Auto Routing (Improved).
* Map of URI segments and namespaces.
*
* The key is the first URI segment. The value is the controller namespace.
* E.g.,
* [
* 'blog' => 'Acme\Blog\Controllers',
* ]
*
* @var array<string, string>
*/
public array $moduleRoutes = [];
/**
* For Auto Routing (Improved).
* Whether to translate dashes in URIs for controller/method to CamelCase.
* E.g., blog-controller -> BlogController
*
* If you enable this, $translateURIDashes is ignored.
*
* Default: false
*/
public bool $translateUriToCamelCase = true;
}

86
app/Config/Security.php Normal file
View File

@@ -0,0 +1,86 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Security extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* CSRF Protection Method
* --------------------------------------------------------------------------
*
* Protection Method for Cross Site Request Forgery protection.
*
* @var string 'cookie' or 'session'
*/
public string $csrfProtection = 'cookie';
/**
* --------------------------------------------------------------------------
* CSRF Token Randomization
* --------------------------------------------------------------------------
*
* Randomize the CSRF Token for added security.
*/
public bool $tokenRandomize = false;
/**
* --------------------------------------------------------------------------
* CSRF Token Name
* --------------------------------------------------------------------------
*
* Token name for Cross Site Request Forgery protection.
*/
public string $tokenName = 'csrf_test_name';
/**
* --------------------------------------------------------------------------
* CSRF Header Name
* --------------------------------------------------------------------------
*
* Header name for Cross Site Request Forgery protection.
*/
public string $headerName = 'X-CSRF-TOKEN';
/**
* --------------------------------------------------------------------------
* CSRF Cookie Name
* --------------------------------------------------------------------------
*
* Cookie name for Cross Site Request Forgery protection.
*/
public string $cookieName = 'csrf_cookie_name';
/**
* --------------------------------------------------------------------------
* CSRF Expires
* --------------------------------------------------------------------------
*
* Expiration time for Cross Site Request Forgery protection cookie.
*
* Defaults to two hours (in seconds).
*/
public int $expires = 7200;
/**
* --------------------------------------------------------------------------
* CSRF Regenerate
* --------------------------------------------------------------------------
*
* Regenerate CSRF Token on every submission.
*/
public bool $regenerate = true;
/**
* --------------------------------------------------------------------------
* CSRF Redirect
* --------------------------------------------------------------------------
*
* Redirect to previous page with error on failure.
*
* @see https://codeigniter4.github.io/userguide/libraries/security.html#redirection-on-failure
*/
public bool $redirect = (ENVIRONMENT === 'production');
}

32
app/Config/Services.php Normal file
View File

@@ -0,0 +1,32 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseService;
/**
* Services Configuration file.
*
* Services are simply other classes/libraries that the system uses
* to do its job. This is used by CodeIgniter to allow the core of the
* framework to be swapped out easily without affecting the usage within
* the rest of your application.
*
* This file holds any application-specific services, or service overrides
* that you might need. An example has been included with the general
* method format you should use for your service methods. For more examples,
* see the core Services file at system/Config/Services.php.
*/
class Services extends BaseService
{
/*
* public static function example($getShared = true)
* {
* if ($getShared) {
* return static::getSharedInstance('example');
* }
*
* return new \CodeIgniter\Example();
* }
*/
}

128
app/Config/Session.php Normal file
View File

@@ -0,0 +1,128 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Session\Handlers\BaseHandler;
use CodeIgniter\Session\Handlers\FileHandler;
class Session extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Session Driver
* --------------------------------------------------------------------------
*
* The session storage driver to use:
* - `CodeIgniter\Session\Handlers\ArrayHandler` (for testing)
* - `CodeIgniter\Session\Handlers\FileHandler`
* - `CodeIgniter\Session\Handlers\DatabaseHandler`
* - `CodeIgniter\Session\Handlers\MemcachedHandler`
* - `CodeIgniter\Session\Handlers\RedisHandler`
*
* @var class-string<BaseHandler>
*/
public string $driver = FileHandler::class;
/**
* --------------------------------------------------------------------------
* Session Cookie Name
* --------------------------------------------------------------------------
*
* The session cookie name, must contain only [0-9a-z_-] characters
*/
public string $cookieName = 'ci_session';
/**
* --------------------------------------------------------------------------
* Session Expiration
* --------------------------------------------------------------------------
*
* The number of SECONDS you want the session to last.
* Setting to 0 (zero) means expire when the browser is closed.
*/
public int $expiration = 7200;
/**
* --------------------------------------------------------------------------
* Session Save Path
* --------------------------------------------------------------------------
*
* The location to save sessions to and is driver dependent.
*
* For the 'files' driver, it's a path to a writable directory.
* WARNING: Only absolute paths are supported!
*
* For the 'database' driver, it's a table name.
* Please read up the manual for the format with other session drivers.
*
* IMPORTANT: You are REQUIRED to set a valid save path!
*/
public string $savePath = WRITEPATH . 'session';
/**
* --------------------------------------------------------------------------
* Session Match IP
* --------------------------------------------------------------------------
*
* Whether to match the user's IP address when reading the session data.
*
* WARNING: If you're using the database driver, don't forget to update
* your session table's PRIMARY KEY when changing this setting.
*/
public bool $matchIP = false;
/**
* --------------------------------------------------------------------------
* Session Time to Update
* --------------------------------------------------------------------------
*
* How many seconds between CI regenerating the session ID.
*/
public int $timeToUpdate = 300;
/**
* --------------------------------------------------------------------------
* Session Regenerate Destroy
* --------------------------------------------------------------------------
*
* Whether to destroy session data associated with the old session ID
* when auto-regenerating the session ID. When set to FALSE, the data
* will be later deleted by the garbage collector.
*/
public bool $regenerateDestroy = false;
/**
* --------------------------------------------------------------------------
* Session Database Group
* --------------------------------------------------------------------------
*
* DB Group for the database session.
*/
public ?string $DBGroup = null;
/**
* --------------------------------------------------------------------------
* Lock Retry Interval (microseconds)
* --------------------------------------------------------------------------
*
* This is used for RedisHandler.
*
* Time (microseconds) to wait if lock cannot be acquired.
* The default is 100,000 microseconds (= 0.1 seconds).
*/
public int $lockRetryInterval = 100_000;
/**
* --------------------------------------------------------------------------
* Lock Max Retries
* --------------------------------------------------------------------------
*
* This is used for RedisHandler.
*
* Maximum number of lock acquisition attempts.
* The default is 300 times. That is lock timeout is about 30 (0.1 * 300)
* seconds.
*/
public int $lockMaxRetries = 300;
}

147
app/Config/Toolbar.php Normal file
View File

@@ -0,0 +1,147 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Debug\Toolbar\Collectors\Database;
use CodeIgniter\Debug\Toolbar\Collectors\Events;
use CodeIgniter\Debug\Toolbar\Collectors\Files;
use CodeIgniter\Debug\Toolbar\Collectors\Logs;
use CodeIgniter\Debug\Toolbar\Collectors\Routes;
use CodeIgniter\Debug\Toolbar\Collectors\Timers;
use CodeIgniter\Debug\Toolbar\Collectors\Views;
/**
* --------------------------------------------------------------------------
* Debug Toolbar
* --------------------------------------------------------------------------
*
* The Debug Toolbar provides a way to see information about the performance
* and state of your application during that page display. By default it will
* NOT be displayed under production environments, and will only display if
* `CI_DEBUG` is true, since if it's not, there's not much to display anyway.
*/
class Toolbar extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Toolbar Collectors
* --------------------------------------------------------------------------
*
* List of toolbar collectors that will be called when Debug Toolbar
* fires up and collects data from.
*
* @var list<class-string>
*/
public array $collectors = [
Timers::class,
Database::class,
Logs::class,
Views::class,
// \CodeIgniter\Debug\Toolbar\Collectors\Cache::class,
Files::class,
Routes::class,
Events::class,
];
/**
* --------------------------------------------------------------------------
* Collect Var Data
* --------------------------------------------------------------------------
*
* If set to false var data from the views will not be collected. Useful to
* avoid high memory usage when there are lots of data passed to the view.
*/
public bool $collectVarData = true;
/**
* --------------------------------------------------------------------------
* Max History
* --------------------------------------------------------------------------
*
* `$maxHistory` sets a limit on the number of past requests that are stored,
* helping to conserve file space used to store them. You can set it to
* 0 (zero) to not have any history stored, or -1 for unlimited history.
*/
public int $maxHistory = 20;
/**
* --------------------------------------------------------------------------
* Toolbar Views Path
* --------------------------------------------------------------------------
*
* The full path to the the views that are used by the toolbar.
* This MUST have a trailing slash.
*/
public string $viewsPath = SYSTEMPATH . 'Debug/Toolbar/Views/';
/**
* --------------------------------------------------------------------------
* Max Queries
* --------------------------------------------------------------------------
*
* If the Database Collector is enabled, it will log every query that the
* the system generates so they can be displayed on the toolbar's timeline
* and in the query log. This can lead to memory issues in some instances
* with hundreds of queries.
*
* `$maxQueries` defines the maximum amount of queries that will be stored.
*/
public int $maxQueries = 100;
/**
* --------------------------------------------------------------------------
* Watched Directories
* --------------------------------------------------------------------------
*
* Contains an array of directories that will be watched for changes and
* used to determine if the hot-reload feature should reload the page or not.
* We restrict the values to keep performance as high as possible.
*
* NOTE: The ROOTPATH will be prepended to all values.
*
* @var list<string>
*/
public array $watchedDirectories = [
'app',
];
/**
* --------------------------------------------------------------------------
* Watched File Extensions
* --------------------------------------------------------------------------
*
* Contains an array of file extensions that will be watched for changes and
* used to determine if the hot-reload feature should reload the page or not.
*
* @var list<string>
*/
public array $watchedExtensions = [
'php', 'css', 'js', 'html', 'svg', 'json', 'env',
];
/**
* --------------------------------------------------------------------------
* Ignored HTTP Headers
* --------------------------------------------------------------------------
*
* CodeIgniter Debug Toolbar normally injects HTML and JavaScript into every
* HTML response. This is correct for full page loads, but it breaks requests
* that expect only a clean HTML fragment.
*
* Libraries like HTMX, Unpoly, and Hotwire (Turbo) update parts of the page or
* manage navigation on the client side. Injecting the Debug Toolbar into their
* responses can cause invalid HTML, duplicated scripts, or JavaScript errors
* (such as infinite loops or "Maximum call stack size exceeded").
*
* Any request containing one of the following headers is treated as a
* client-managed or partial request, and the Debug Toolbar injection is skipped.
*
* @var array<string, string|null>
*/
public array $disableOnHeaders = [
'X-Requested-With' => 'xmlhttprequest', // AJAX requests
'HX-Request' => 'true', // HTMX requests
'X-Up-Version' => null, // Unpoly partial requests
];
}

262
app/Config/UserAgents.php Normal file
View File

@@ -0,0 +1,262 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* -------------------------------------------------------------------
* User Agents
* -------------------------------------------------------------------
*
* This file contains four arrays of user agent data. It is used by the
* User Agent Class to help identify browser, platform, robot, and
* mobile device data. The array keys are used to identify the device
* and the array values are used to set the actual name of the item.
*/
class UserAgents extends BaseConfig
{
/**
* -------------------------------------------------------------------
* OS Platforms
* -------------------------------------------------------------------
*
* @var array<string, string>
*/
public array $platforms = [
'windows nt 10.0' => 'Windows 10',
'windows nt 6.3' => 'Windows 8.1',
'windows nt 6.2' => 'Windows 8',
'windows nt 6.1' => 'Windows 7',
'windows nt 6.0' => 'Windows Vista',
'windows nt 5.2' => 'Windows 2003',
'windows nt 5.1' => 'Windows XP',
'windows nt 5.0' => 'Windows 2000',
'windows nt 4.0' => 'Windows NT 4.0',
'winnt4.0' => 'Windows NT 4.0',
'winnt 4.0' => 'Windows NT',
'winnt' => 'Windows NT',
'windows 98' => 'Windows 98',
'win98' => 'Windows 98',
'windows 95' => 'Windows 95',
'win95' => 'Windows 95',
'windows phone' => 'Windows Phone',
'windows' => 'Unknown Windows OS',
'android' => 'Android',
'blackberry' => 'BlackBerry',
'iphone' => 'iOS',
'ipad' => 'iOS',
'ipod' => 'iOS',
'os x' => 'Mac OS X',
'ppc mac' => 'Power PC Mac',
'freebsd' => 'FreeBSD',
'ppc' => 'Macintosh',
'linux' => 'Linux',
'debian' => 'Debian',
'sunos' => 'Sun Solaris',
'beos' => 'BeOS',
'apachebench' => 'ApacheBench',
'aix' => 'AIX',
'irix' => 'Irix',
'osf' => 'DEC OSF',
'hp-ux' => 'HP-UX',
'netbsd' => 'NetBSD',
'bsdi' => 'BSDi',
'openbsd' => 'OpenBSD',
'gnu' => 'GNU/Linux',
'unix' => 'Unknown Unix OS',
'symbian' => 'Symbian OS',
];
/**
* -------------------------------------------------------------------
* Browsers
* -------------------------------------------------------------------
*
* The order of this array should NOT be changed. Many browsers return
* multiple browser types so we want to identify the subtype first.
*
* @var array<string, string>
*/
public array $browsers = [
'OPR' => 'Opera',
'Flock' => 'Flock',
'Edge' => 'Spartan',
'Edg' => 'Edge',
'Chrome' => 'Chrome',
// Opera 10+ always reports Opera/9.80 and appends Version/<real version> to the user agent string
'Opera.*?Version' => 'Opera',
'Opera' => 'Opera',
'MSIE' => 'Internet Explorer',
'Internet Explorer' => 'Internet Explorer',
'Trident.* rv' => 'Internet Explorer',
'Shiira' => 'Shiira',
'Firefox' => 'Firefox',
'Chimera' => 'Chimera',
'Phoenix' => 'Phoenix',
'Firebird' => 'Firebird',
'Camino' => 'Camino',
'Netscape' => 'Netscape',
'OmniWeb' => 'OmniWeb',
'Safari' => 'Safari',
'Mozilla' => 'Mozilla',
'Konqueror' => 'Konqueror',
'icab' => 'iCab',
'Lynx' => 'Lynx',
'Links' => 'Links',
'hotjava' => 'HotJava',
'amaya' => 'Amaya',
'IBrowse' => 'IBrowse',
'Maxthon' => 'Maxthon',
'Ubuntu' => 'Ubuntu Web Browser',
'Vivaldi' => 'Vivaldi',
];
/**
* -------------------------------------------------------------------
* Mobiles
* -------------------------------------------------------------------
*
* @var array<string, string>
*/
public array $mobiles = [
// legacy array, old values commented out
'mobileexplorer' => 'Mobile Explorer',
// 'openwave' => 'Open Wave',
// 'opera mini' => 'Opera Mini',
// 'operamini' => 'Opera Mini',
// 'elaine' => 'Palm',
'palmsource' => 'Palm',
// 'digital paths' => 'Palm',
// 'avantgo' => 'Avantgo',
// 'xiino' => 'Xiino',
'palmscape' => 'Palmscape',
// 'nokia' => 'Nokia',
// 'ericsson' => 'Ericsson',
// 'blackberry' => 'BlackBerry',
// 'motorola' => 'Motorola'
// Phones and Manufacturers
'motorola' => 'Motorola',
'nokia' => 'Nokia',
'palm' => 'Palm',
'iphone' => 'Apple iPhone',
'ipad' => 'iPad',
'ipod' => 'Apple iPod Touch',
'sony' => 'Sony Ericsson',
'ericsson' => 'Sony Ericsson',
'blackberry' => 'BlackBerry',
'cocoon' => 'O2 Cocoon',
'blazer' => 'Treo',
'lg' => 'LG',
'amoi' => 'Amoi',
'xda' => 'XDA',
'mda' => 'MDA',
'vario' => 'Vario',
'htc' => 'HTC',
'samsung' => 'Samsung',
'sharp' => 'Sharp',
'sie-' => 'Siemens',
'alcatel' => 'Alcatel',
'benq' => 'BenQ',
'ipaq' => 'HP iPaq',
'mot-' => 'Motorola',
'playstation portable' => 'PlayStation Portable',
'playstation 3' => 'PlayStation 3',
'playstation vita' => 'PlayStation Vita',
'hiptop' => 'Danger Hiptop',
'nec-' => 'NEC',
'panasonic' => 'Panasonic',
'philips' => 'Philips',
'sagem' => 'Sagem',
'sanyo' => 'Sanyo',
'spv' => 'SPV',
'zte' => 'ZTE',
'sendo' => 'Sendo',
'nintendo dsi' => 'Nintendo DSi',
'nintendo ds' => 'Nintendo DS',
'nintendo 3ds' => 'Nintendo 3DS',
'wii' => 'Nintendo Wii',
'open web' => 'Open Web',
'openweb' => 'OpenWeb',
// Operating Systems
'android' => 'Android',
'symbian' => 'Symbian',
'SymbianOS' => 'SymbianOS',
'elaine' => 'Palm',
'series60' => 'Symbian S60',
'windows ce' => 'Windows CE',
// Browsers
'obigo' => 'Obigo',
'netfront' => 'Netfront Browser',
'openwave' => 'Openwave Browser',
'mobilexplorer' => 'Mobile Explorer',
'operamini' => 'Opera Mini',
'opera mini' => 'Opera Mini',
'opera mobi' => 'Opera Mobile',
'fennec' => 'Firefox Mobile',
// Other
'digital paths' => 'Digital Paths',
'avantgo' => 'AvantGo',
'xiino' => 'Xiino',
'novarra' => 'Novarra Transcoder',
'vodafone' => 'Vodafone',
'docomo' => 'NTT DoCoMo',
'o2' => 'O2',
// Fallback
'mobile' => 'Generic Mobile',
'wireless' => 'Generic Mobile',
'j2me' => 'Generic Mobile',
'midp' => 'Generic Mobile',
'cldc' => 'Generic Mobile',
'up.link' => 'Generic Mobile',
'up.browser' => 'Generic Mobile',
'smartphone' => 'Generic Mobile',
'cellphone' => 'Generic Mobile',
];
/**
* -------------------------------------------------------------------
* Robots
* -------------------------------------------------------------------
*
* There are hundred of bots but these are the most common.
*
* @var array<string, string>
*/
public array $robots = [
'googlebot' => 'Googlebot',
'google-pagerenderer' => 'Google Page Renderer',
'google-read-aloud' => 'Google Read Aloud',
'google-safety' => 'Google Safety Bot',
'msnbot' => 'MSNBot',
'baiduspider' => 'Baiduspider',
'bingbot' => 'Bing',
'bingpreview' => 'BingPreview',
'slurp' => 'Inktomi Slurp',
'yahoo' => 'Yahoo',
'ask jeeves' => 'Ask Jeeves',
'fastcrawler' => 'FastCrawler',
'infoseek' => 'InfoSeek Robot 1.0',
'lycos' => 'Lycos',
'yandex' => 'YandexBot',
'mediapartners-google' => 'MediaPartners Google',
'CRAZYWEBCRAWLER' => 'Crazy Webcrawler',
'adsbot-google' => 'AdsBot Google',
'feedfetcher-google' => 'Feedfetcher Google',
'curious george' => 'Curious George',
'ia_archiver' => 'Alexa Crawler',
'MJ12bot' => 'Majestic-12',
'Uptimebot' => 'Uptimebot',
'duckduckbot' => 'DuckDuckBot',
'sogou' => 'Sogou Spider',
'exabot' => 'Exabot',
'bot' => 'Generic Bot',
'crawler' => 'Generic Crawler',
'spider' => 'Generic Spider',
];
}

44
app/Config/Validation.php Normal file
View File

@@ -0,0 +1,44 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Validation\StrictRules\CreditCardRules;
use CodeIgniter\Validation\StrictRules\FileRules;
use CodeIgniter\Validation\StrictRules\FormatRules;
use CodeIgniter\Validation\StrictRules\Rules;
class Validation extends BaseConfig
{
// --------------------------------------------------------------------
// Setup
// --------------------------------------------------------------------
/**
* Stores the classes that contain the
* rules that are available.
*
* @var list<string>
*/
public array $ruleSets = [
Rules::class,
FormatRules::class,
FileRules::class,
CreditCardRules::class,
];
/**
* Specifies the views that are used to display the
* errors.
*
* @var array<string, string>
*/
public array $templates = [
'list' => 'CodeIgniter\Validation\Views\list',
'single' => 'CodeIgniter\Validation\Views\single',
];
// --------------------------------------------------------------------
// Rules
// --------------------------------------------------------------------
}

79
app/Config/View.php Normal file
View File

@@ -0,0 +1,79 @@
<?php
namespace Config;
use CodeIgniter\Config\View as BaseView;
use CodeIgniter\View\ViewDecoratorInterface;
/**
* @phpstan-type parser_callable (callable(mixed): mixed)
* @phpstan-type parser_callable_string (callable(mixed): mixed)&string
*/
class View extends BaseView
{
/**
* When false, the view method will clear the data between each
* call. This keeps your data safe and ensures there is no accidental
* leaking between calls, so you would need to explicitly pass the data
* to each view. You might prefer to have the data stick around between
* calls so that it is available to all views. If that is the case,
* set $saveData to true.
*
* @var bool
*/
public $saveData = true;
/**
* Parser Filters map a filter name with any PHP callable. When the
* Parser prepares a variable for display, it will chain it
* through the filters in the order defined, inserting any parameters.
* To prevent potential abuse, all filters MUST be defined here
* in order for them to be available for use within the Parser.
*
* Examples:
* { title|esc(js) }
* { created_on|date(Y-m-d)|esc(attr) }
*
* @var array<string, string>
* @phpstan-var array<string, parser_callable_string>
*/
public $filters = [];
/**
* Parser Plugins provide a way to extend the functionality provided
* by the core Parser by creating aliases that will be replaced with
* any callable. Can be single or tag pair.
*
* @var array<string, callable|list<string>|string>
* @phpstan-var array<string, list<parser_callable_string>|parser_callable_string|parser_callable>
*/
public $plugins = [];
/**
* View Decorators are class methods that will be run in sequence to
* have a chance to alter the generated output just prior to caching
* the results.
*
* All classes must implement CodeIgniter\View\ViewDecoratorInterface
*
* @var list<class-string<ViewDecoratorInterface>>
*/
public array $decorators = [];
/**
* Subdirectory within app/Views for namespaced view overrides.
*
* Namespaced views will be searched in:
*
* app/Views/{$appOverridesFolder}/{Namespace}/{view_path}.{php|html...}
*
* This allows application-level overrides for package or module views
* without modifying vendor source files.
*
* Examples:
* 'overrides' -> app/Views/overrides/Example/Blog/post/card.php
* 'vendor' -> app/Views/vendor/Example/Blog/post/card.php
* '' -> app/Views/Example/Blog/post/card.php (direct mapping)
*/
public string $appOverridesFolder = 'overrides';
}

62
app/Config/WorkerMode.php Normal file
View File

@@ -0,0 +1,62 @@
<?php
namespace Config;
/**
* This configuration controls how CodeIgniter behaves when running
* in worker mode (with FrankenPHP).
*/
class WorkerMode
{
/**
* Persistent Services
*
* List of service names that should persist across requests.
* These services will NOT be reset between requests.
*
* Services not in this list will be reset for each request to prevent
* state leakage.
*
* Recommended persistent services:
* - `autoloader`: PSR-4 autoloading configuration
* - `locator`: File locator
* - `exceptions`: Exception handler
* - `commands`: CLI commands registry
* - `codeigniter`: Main application instance
* - `superglobals`: Superglobals wrapper
* - `routes`: Router configuration
* - `cache`: Cache instance
*
* @var list<string>
*/
public array $persistentServices = [
'autoloader',
'locator',
'exceptions',
'commands',
'codeigniter',
'superglobals',
'routes',
'cache',
];
/**
* Reset Event Listeners
*
* List of event names whose listeners should be removed between requests.
* Use this if you register event listeners inside other event callbacks
* (rather than at the top level of Config/Events.php), which would cause
* them to accumulate across requests in worker mode.
*
* @var list<string>
*/
public array $resetEventListeners = [];
/**
* Force Garbage Collection
*
* Whether to force garbage collection after each request.
* Helps prevent memory leaks at a small performance cost.
*/
public bool $forceGarbageCollection = true;
}

View File

@@ -0,0 +1,112 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Admin;
use App\Controllers\BaseController;
use App\Services\Admin\AdminUsersLoginService;
use App\Services\ApiClient;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Login admin → token API mobile disimpan di sesi.
*/
class Auth extends BaseController
{
public function login(): ResponseInterface|string
{
if (session()->get('admin_mobile_token')) {
return redirect()->to(site_url('admin'));
}
return view('admin/auth/login');
}
public function attempt(): RedirectResponse
{
$user = (string) $this->request->getPost('username');
$pass = (string) $this->request->getPost('password');
$client = new ApiClient();
$res = $client->postMobile('login', [
'username' => $user,
'password' => $pass,
]);
$json = $res['json'];
if ($res['transport_ok'] && ApiClient::isSuccess($json) && is_array($json) && ! empty($json['token'])) {
$token = (string) $json['token'];
$loginSvc = new AdminUsersLoginService();
$pid = $loginSvc->resolvePegawaiIdFromCredentials($user);
$linked = ($pid !== null && $pid > 0) ? $loginSvc->findLinkedAdminForPegawaiId($pid) : null;
if ($linked !== null) {
$dispUser = $linked['username'] !== '' ? $linked['username'] : $user;
session()->set([
'admin_mobile_token' => $token,
'admin_username' => $dispUser,
'admin_auth_source' => 'admin_users',
'admin_ion_user_id' => $linked['admin_user_id'],
'admin_ion_groups' => $linked['group_names'],
]);
return redirect()->to(site_url('admin'))->with('message', 'Login berhasil (akun admin / grup terhubung).');
}
session()->remove(['admin_ion_user_id', 'admin_ion_groups']);
session()->set([
'admin_mobile_token' => $token,
'admin_username' => $user,
'admin_auth_source' => 'pegawai',
]);
return redirect()->to(site_url('admin'))->with('message', 'Login berhasil.');
}
$ion = (new AdminUsersLoginService())->tryLogin($user, $pass);
if (($ion['ok'] ?? false) === true) {
session()->set([
'admin_mobile_token' => (string) $ion['token'],
'admin_username' => (string) $ion['username'],
'admin_auth_source' => 'admin_users',
'admin_ion_user_id' => (int) $ion['admin_user_id'],
'admin_ion_groups' => $ion['group_names'],
]);
return redirect()->to(site_url('admin'))->with('message', 'Login berhasil (Ion Auth / admin_users).');
}
if (($ion['reason'] ?? '') === 'no_group') {
return redirect()->back()->withInput()->with(
'error',
'Akun admin_users tidak memiliki grup di admin_users_groups — login ditolak (sesuai struktur Ion Auth).'
);
}
if (($ion['reason'] ?? '') === 'no_proxy') {
return redirect()->back()->withInput()->with(
'error',
'Akun admin_users valid, tetapi tidak ada pegawai untuk token API. Isi ADMIN_LOGIN_PROXY_PEGAWAI_ID di .env (id_pegawai) atau pastikan tabel pegawai berisi data.'
);
}
$msg = is_array($json) ? (string) ($json['pesan'] ?? 'Login gagal.') : ($res['error'] ?? 'Login gagal.');
return redirect()->back()->withInput()->with('error', $msg);
}
public function logout(): RedirectResponse
{
session()->remove([
'admin_mobile_token',
'admin_username',
'admin_auth_source',
'admin_ion_user_id',
'admin_ion_groups',
]);
return redirect()->to(site_url('admin/login'))->with('message', 'Anda telah keluar.');
}
}

View File

@@ -0,0 +1,112 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Admin;
use App\Controllers\BaseController;
use App\Services\ApiClient;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
abstract class BaseAdminController extends BaseController
{
protected ApiClient $apiClient;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger): void
{
parent::initController($request, $response, $logger);
helper('rbac');
$this->apiClient = new ApiClient();
}
/**
* RBAC fitur (`Config\AdminAccess` + `canAccess()`). Null = boleh lanjut.
*/
protected function enforceAccess(string $feature): ?ResponseInterface
{
if (canAccess($feature)) {
return null;
}
if ($this->request->isAJAX()) {
return $this->response->setStatusCode(403)->setJSON([
'status' => 0,
'pesan' => 'Akses ditolak untuk peran Anda.',
]);
}
return redirect()->to(site_url('admin'))->with('error', 'Akses ditolak untuk peran Anda.');
}
protected function adminToken(): ?string
{
$t = session()->get('admin_mobile_token');
return is_string($t) && $t !== '' ? $t : null;
}
/**
* @param array<string, scalar|null> $extra
*
* @return array{transport_ok: bool, http_code: int, json: array<string, mixed>|null, error: string|null, raw: string}
*/
protected function apiMobile(string $method, array $extra = []): array
{
$token = $this->adminToken();
if ($token === null) {
return [
'transport_ok' => false,
'http_code' => 0,
'json' => null,
'error' => 'Belum login — tidak ada token API.',
'raw' => '',
];
}
return $this->apiClient->postMobileWithToken($method, $token, $extra);
}
/**
* @param array<string, scalar|null> $query
*
* @return array{transport_ok: bool, http_code: int, json: array<string, mixed>|null, error: string|null, raw: string}
*/
protected function apiAdminGet(string $path, array $query = []): array
{
$token = $this->adminToken();
if ($token === null) {
return [
'transport_ok' => false,
'http_code' => 0,
'json' => null,
'error' => 'Belum login — tidak ada token API.',
'raw' => '',
];
}
return $this->apiClient->getAdmin($path, $token, $query);
}
/**
* @param array<string, scalar|null> $form
*
* @return array{transport_ok: bool, http_code: int, json: array<string, mixed>|null, error: string|null, raw: string}
*/
protected function apiAdminPost(string $path, array $form = []): array
{
$token = $this->adminToken();
if ($token === null) {
return [
'transport_ok' => false,
'http_code' => 0,
'json' => null,
'error' => 'Belum login — tidak ada token API.',
'raw' => '',
];
}
return $this->apiClient->postAdmin($path, $token, $form);
}
}

View File

@@ -0,0 +1,267 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Admin;
use App\Services\ApiClient;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Master perusahaan — memanggil `/api/admin/company/*`.
*/
class Company extends BaseAdminController
{
public function kantor(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('perusahaan')) !== null) {
return $deny;
}
return $this->loadExtra('company/kantor', 'admin/perusahaan/kantor');
}
public function kantorSave(): ResponseInterface
{
if (($deny = $this->enforceAccess('perusahaan')) !== null) {
return $deny;
}
return $this->postExtra('company/kantor/save', 'admin/perusahaan/kantor');
}
public function kantorDelete(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('perusahaan')) !== null) {
return $deny;
}
return $this->postExtra('company/kantor/delete/' . $id, 'admin/perusahaan/kantor', []);
}
public function unitKerja(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('perusahaan')) !== null) {
return $deny;
}
return $this->loadExtra('company/unit_kerja', 'admin/perusahaan/unit_kerja');
}
public function unitKerjaSave(): ResponseInterface
{
if (($deny = $this->enforceAccess('perusahaan')) !== null) {
return $deny;
}
return $this->postExtra('company/unit_kerja/save', 'admin/perusahaan/unit_kerja');
}
public function unitKerjaDelete(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('perusahaan')) !== null) {
return $deny;
}
return $this->postExtra('company/unit_kerja/delete/' . $id, 'admin/perusahaan/unit_kerja', []);
}
public function golongan(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('perusahaan')) !== null) {
return $deny;
}
return $this->loadExtra('company/golongan', 'admin/perusahaan/golongan');
}
public function golonganSave(): ResponseInterface
{
if (($deny = $this->enforceAccess('perusahaan')) !== null) {
return $deny;
}
return $this->postExtra('company/golongan/save', 'admin/perusahaan/golongan');
}
public function golonganDelete(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('perusahaan')) !== null) {
return $deny;
}
return $this->postExtra('company/golongan/delete/' . $id, 'admin/perusahaan/golongan', []);
}
public function jabatan(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('perusahaan')) !== null) {
return $deny;
}
return $this->loadExtra('company/jabatan', 'admin/perusahaan/jabatan');
}
public function jabatanSave(): ResponseInterface
{
if (($deny = $this->enforceAccess('perusahaan')) !== null) {
return $deny;
}
return $this->postExtra('company/jabatan/save', 'admin/perusahaan/jabatan');
}
public function jabatanDelete(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('perusahaan')) !== null) {
return $deny;
}
return $this->postExtra('company/jabatan/delete/' . $id, 'admin/perusahaan/jabatan', []);
}
public function berita(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('perusahaan')) !== null) {
return $deny;
}
return $this->loadExtra('company/berita', 'admin/perusahaan/berita');
}
public function beritaSave(): ResponseInterface
{
if (($deny = $this->enforceAccess('perusahaan')) !== null) {
return $deny;
}
$post = $this->request->getPost() ?? [];
$existing = (string) ($this->request->getPost('photo_existing') ?? '');
if (($err = $this->mergeBeritaPhotoIntoPost($post, $existing)) !== null) {
return redirect()->to(site_url('admin/perusahaan/berita'))->with('error', $err);
}
unset($post['photo_existing']);
$r = $this->apiAdminPost('company/berita/save', $post);
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
return redirect()->to(site_url('admin/perusahaan/berita'))->with('message', (string) ($r['json']['pesan'] ?? 'OK'));
}
$msg = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
return redirect()->to(site_url('admin/perusahaan/berita'))->with('error', $msg);
}
public function beritaDelete(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('perusahaan')) !== null) {
return $deny;
}
return $this->postExtra('company/berita/delete/' . $id, 'admin/perusahaan/berita', []);
}
private function loadExtra(string $apiPath, string $view): string
{
$errors = [];
$data = null;
$r = $this->apiAdminGet($apiPath);
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$data = $r['json']['data'] ?? null;
} else {
$errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal memuat data') : 'Gagal memuat data');
}
return view($view, [
'payload' => is_array($data) ? $data : null,
'errors' => $errors,
]);
}
private function postExtra(string $apiPath, string $redirectUri, ?array $mergePost = null): ResponseInterface
{
$post = array_merge($this->request->getPost(), $mergePost ?? []);
$r = $this->apiAdminPost($apiPath, $post);
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
return redirect()->to(site_url($redirectUri))->with('message', (string) ($r['json']['pesan'] ?? 'OK'));
}
$msg = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
return redirect()->to(site_url($redirectUri))->with('error', $msg);
}
/**
* Selaras CI3: `assets/uploads/berita/`.
*/
private function beritaPhotoUploadDir(): string
{
$base = FCPATH . 'assets' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'berita';
if (! is_dir($base)) {
mkdir($base, 0755, true);
}
return $base;
}
/**
* Unggah ke folder berita atau nama file manual. Kolom DB kosong di API disimpan sebagai '-'.
*
* @param array<string, mixed> $post
*
* @return string|null pesan error, atau null jika OK
*/
private function mergeBeritaPhotoIntoPost(array &$post, string $photoExistingFromDb): ?string
{
$file = $this->request->getFile('photo_file');
if ($file !== null && $file->getError() !== UPLOAD_ERR_NO_FILE) {
if (! $file->isValid()) {
return 'Unggah foto tidak valid.';
}
$mime = (string) $file->getMimeType();
$allowedMime = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (! in_array($mime, $allowedMime, true)) {
return 'Format foto harus JPG, PNG, GIF, atau WebP.';
}
if ($file->getSize() > 2_097_152) {
return 'Ukuran foto maksimal 2 MB.';
}
$ext = strtolower((string) ($file->guessExtension() ?: $file->getClientExtension()));
if (! in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp'], true)) {
return 'Ekstensi foto tidak didukung.';
}
$dir = $this->beritaPhotoUploadDir();
$rawName = pathinfo($file->getClientName(), PATHINFO_FILENAME);
$safeOriginal = preg_replace('/[^A-Za-z0-9._-]+/', '_', (string) $rawName) ?: 'berita';
$safeOriginal = substr($safeOriginal, 0, 80);
$filename = uniqid((string) mt_rand(), true) . '-' . $safeOriginal . '.' . $ext;
if (! $file->move($dir, $filename, true)) {
return 'Gagal menyimpan file foto ke server.';
}
$old = trim($photoExistingFromDb);
if ($old !== '' && $old !== '-' && $old !== $filename) {
$oldPath = $dir . DIRECTORY_SEPARATOR . basename(str_replace('\\', '/', $old));
if (is_file($oldPath)) {
@unlink($oldPath);
}
}
$post['photo'] = $filename;
return null;
}
$manual = isset($post['photo']) ? trim((string) $post['photo']) : '';
if ($manual === '' || $manual === '-') {
$post['photo'] = '';
return null;
}
$base = basename(str_replace('\\', '/', $manual));
if (! preg_match('/^[A-Za-z0-9._-]+$/', $base)) {
return 'Nama file foto hanya boleh huruf, angka, titik, garis bawah, dan tanda hubung (atau unggah file).';
}
$post['photo'] = substr($base, 0, 255);
return null;
}
}

View File

@@ -0,0 +1,153 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Admin;
use App\Services\ApiClient;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Manajemen cuti pegawai (setara `admin/pegawai/cuti` CI3) via `/api/admin/cuti*`.
*/
class Cuti extends BaseAdminController
{
public function index(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('cuti')) !== null) {
return $deny;
}
$status = (string) ($this->request->getGet('status') ?? 'Waiting');
$page = max(1, (int) ($this->request->getGet('page') ?? 1));
$errors = [];
$payload = null;
$r = $this->apiAdminGet('cuti', [
'status' => $status,
'page' => (string) $page,
'per_page' => '30',
]);
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$payload = $r['json']['data'] ?? null;
} else {
$errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal memuat cuti') : 'Gagal memuat cuti');
}
helper('cuti_display');
return view('admin/cuti/index', [
'payload' => $payload,
'errors' => $errors,
'status' => $status,
'page' => $page,
]);
}
/**
* Layani dokumen cuti dari disk (setara file statis CI3 di assets/uploads/dokcuti/).
* Dipakai saat berkas belum dilayani langsung oleh web server (mis. file belum di-copy ke public).
*/
public function dokumen(string $file): ResponseInterface
{
if (($deny = $this->enforceAccess('cuti')) !== null) {
return $deny;
}
$safe = basename(rawurldecode($file));
if ($safe === '' || $safe === '.' || $safe === '..') {
throw PageNotFoundException::forPageNotFound();
}
if (! preg_match('/^[A-Za-z0-9._-]+$/', $safe)) {
throw PageNotFoundException::forPageNotFound();
}
$path = FCPATH . 'assets' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'dokcuti' . DIRECTORY_SEPARATOR . $safe;
if (! is_file($path)) {
throw PageNotFoundException::forPageNotFound(
'Berkas tidak ada di server. Salin isi folder dokcuti dari CI3 ke: public/assets/uploads/dokcuti/',
);
}
$ext = strtolower((string) pathinfo($safe, PATHINFO_EXTENSION));
$mime = match ($ext) {
'jpg', 'jpeg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'webp' => 'image/webp',
'pdf' => 'application/pdf',
default => 'application/octet-stream',
};
$this->response->setHeader('Content-Type', $mime);
$this->response->setHeader('Content-Disposition', 'inline; filename="' . addcslashes($safe, '"\\') . '"');
return $this->response->setBody((string) file_get_contents($path));
}
public function detail(int $id): ResponseInterface|string
{
if (($deny = $this->enforceAccess('cuti')) !== null) {
return $deny;
}
$errors = [];
$bundle = null;
$r = $this->apiAdminGet('cuti/' . $id);
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$bundle = $r['json']['data'] ?? null;
} else {
$errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal memuat detail') : 'Gagal memuat detail');
}
helper('cuti_display');
return view('admin/cuti/detail', [
'bundle' => is_array($bundle) ? $bundle : null,
'errors' => $errors,
'id' => $id,
]);
}
public function approve(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('cuti')) !== null) {
return $deny;
}
$res = $this->apiAdminPost('cuti/approve', ['id_cuti' => (string) $id]);
if ($res['transport_ok'] && ApiClient::isSuccess($res['json'])) {
return redirect()->to(site_url('admin/cuti'))->with('message', (string) ($res['json']['pesan'] ?? 'Disetujui'));
}
$msg = is_array($res['json']) ? (string) ($res['json']['pesan'] ?? 'Gagal') : ($res['error'] ?? 'Gagal');
return redirect()->back()->with('error', $msg);
}
public function reject(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('cuti')) !== null) {
return $deny;
}
$alasan = (string) ($this->request->getPost('alasan_tolak') ?? '');
$res = $this->apiAdminPost('cuti/reject', [
'id_cuti' => (string) $id,
'alasan_tolak' => $alasan,
]);
if ($res['transport_ok'] && ApiClient::isSuccess($res['json'])) {
return redirect()->to(site_url('admin/cuti'))->with('message', (string) ($res['json']['pesan'] ?? 'Ditolak'));
}
$msg = is_array($res['json']) ? (string) ($res['json']['pesan'] ?? 'Gagal') : ($res['error'] ?? 'Gagal');
return redirect()->back()->withInput()->with('error', $msg);
}
}

View File

@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Admin;
use App\Services\ApiClient;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Beranda: statistik admin (`/api/admin/dashboard`) + profil/berita mobile (opsional).
*/
class Dashboard extends BaseAdminController
{
public function index(): string|ResponseInterface
{
if (($deny = $this->enforceAccess('dashboard')) !== null) {
return $deny;
}
$token = $this->adminToken();
$profil = null;
$berita = null;
$errors = [];
$summary = null;
if ($token === null) {
$errors[] = 'Silakan login untuk memuat data dari API.';
} else {
$d = $this->apiAdminGet('dashboard');
if ($d['transport_ok'] && ApiClient::isSuccess($d['json'])) {
$summary = $d['json']['data'] ?? null;
} else {
$errors[] = $d['error'] ?? (is_array($d['json']) ? (string) ($d['json']['pesan'] ?? 'Ringkasan dashboard tidak dapat dimuat.') : 'Ringkasan dashboard tidak dapat dimuat.');
}
$p = $this->apiMobile('profil', []);
if ($p['transport_ok'] && ApiClient::isSuccess($p['json'])) {
$profil = $p['json']['pegawai'] ?? null;
} else {
$errors[] = $p['error'] ?? (is_array($p['json']) ? (string) ($p['json']['pesan'] ?? 'Profil tidak dapat dimuat.') : 'Profil tidak dapat dimuat.');
}
$b = $this->apiMobile('berita', ['dari' => '0', 'jumlah' => '5']);
if ($b['transport_ok'] && ApiClient::isSuccess($b['json'])) {
$berita = $b['json']['data'] ?? [];
} else {
$errors[] = $b['error'] ?? (is_array($b['json']) ? (string) ($b['json']['pesan'] ?? 'Berita tidak dapat dimuat.') : 'Berita tidak dapat dimuat.');
}
}
helper('cuti_display');
return view('admin/dashboard/index', [
'summary' => is_array($summary) ? $summary : null,
'profil' => $profil,
'berita' => is_array($berita) ? $berita : [],
'errors' => $errors,
'token' => $token !== null,
]);
}
}

View File

@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Admin;
use App\Services\ApiClient;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Ringkasan laporan (dashboard angka) lewat `/api/admin/laporan`.
*/
class Laporan extends BaseAdminController
{
public function index(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('laporan')) !== null) {
return $deny;
}
$today = date('Y-m-d');
$dari = (string) ($this->request->getGet('dari') ?? $today);
$sampai = (string) ($this->request->getGet('sampai') ?? $today);
$errors = [];
$summary = null;
$r = $this->apiAdminGet('laporan', ['dari' => $dari, 'sampai' => $sampai]);
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$summary = $r['json']['data'] ?? null;
} else {
$errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal memuat laporan') : 'Gagal memuat laporan');
}
return view('admin/laporan/index', [
'summary' => is_array($summary) ? $summary : null,
'errors' => $errors,
'dari' => $dari,
'sampai' => $sampai,
]);
}
public function cuti(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('laporan')) !== null) {
return $deny;
}
$today = date('Y-m-d');
$dari = (string) ($this->request->getGet('dari') ?? $today);
$sampai = (string) ($this->request->getGet('sampai') ?? $today);
$errors = [];
$rows = [];
$meta = ['dari' => $dari, 'sampai' => $sampai];
$r = $this->apiAdminGet('laporan/cuti', ['dari' => $dari, 'sampai' => $sampai]);
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$d = $r['json']['data'] ?? [];
$rows = is_array($d['rows'] ?? null) ? $d['rows'] : [];
$meta = [
'dari' => (string) ($d['dari'] ?? $dari),
'sampai' => (string) ($d['sampai'] ?? $sampai),
];
} else {
$errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
}
return view('admin/laporan/cuti', [
'rows' => $rows,
'errors' => $errors,
'dari' => $meta['dari'],
'sampai' => $meta['sampai'],
]);
}
}

View File

@@ -0,0 +1,308 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Admin;
use App\Services\ApiClient;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Panel pengguna admin (Ion) — API `/api/admin/panel/*`.
*/
class Panel extends BaseAdminController
{
public function users(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('panel')) !== null) {
return $deny;
}
$errors = [];
$rows = [];
$r = $this->apiAdminGet('panel/users');
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$d = $r['json']['data'] ?? [];
$rows = is_array($d['rows'] ?? null) ? $d['rows'] : [];
} else {
$errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
}
return view('admin/panel/users', ['rows' => $rows, 'errors' => $errors]);
}
public function groups(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('panel')) !== null) {
return $deny;
}
$errors = [];
$rows = [];
$r = $this->apiAdminGet('panel/groups');
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$d = $r['json']['data'] ?? [];
$rows = is_array($d['rows'] ?? null) ? $d['rows'] : [];
} else {
$errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
}
return view('admin/panel/groups', ['rows' => $rows, 'errors' => $errors]);
}
public function groupCreate(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('panel')) !== null) {
return $deny;
}
return view('admin/panel/group_create', ['errors' => []]);
}
public function groupStore(): ResponseInterface
{
if (($deny = $this->enforceAccess('panel')) !== null) {
return $deny;
}
$r = $this->apiAdminPost('panel/groups/create', $this->request->getPost());
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
return redirect()->to(site_url('admin/panel/groups'))->with('message', (string) ($r['json']['pesan'] ?? 'OK'));
}
$msg = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
return redirect()->to(site_url('admin/panel/groups/create'))->withInput()->with('error', $msg);
}
public function groupEdit(int $id): ResponseInterface|string
{
if (($deny = $this->enforceAccess('panel')) !== null) {
return $deny;
}
$errors = [];
$row = null;
$r = $this->apiAdminGet('panel/groups');
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$d = $r['json']['data'] ?? [];
$list = is_array($d['rows'] ?? null) ? $d['rows'] : [];
foreach ($list as $g) {
if ((int) ($g['id'] ?? 0) === $id) {
$row = $g;
break;
}
}
if ($row === null) {
$errors[] = 'Grup tidak ditemukan.';
}
} else {
$errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
}
if ($row === null && $errors === []) {
$errors[] = 'Grup tidak ditemukan.';
}
return view('admin/panel/group_edit', ['id' => $id, 'row' => $row, 'errors' => $errors]);
}
public function groupUpdate(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('panel')) !== null) {
return $deny;
}
$r = $this->apiAdminPost('panel/groups/update/' . $id, $this->request->getPost());
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
return redirect()->to(site_url('admin/panel/groups'))->with('message', (string) ($r['json']['pesan'] ?? 'OK'));
}
$msg = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
return redirect()->to(site_url('admin/panel/groups/edit/' . $id))->withInput()->with('error', $msg);
}
public function groupDelete(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('panel')) !== null) {
return $deny;
}
$r = $this->apiAdminPost('panel/groups/delete/' . $id, $this->request->getPost());
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
return redirect()->to(site_url('admin/panel/groups'))->with('message', (string) ($r['json']['pesan'] ?? 'OK'));
}
$msg = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
return redirect()->to(site_url('admin/panel/groups'))->with('error', $msg);
}
public function userCreate(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('panel')) !== null) {
return $deny;
}
$errors = [];
$groups = [];
$pegawaiRows = [];
$r = $this->apiAdminGet('panel/groups');
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$d = $r['json']['data'] ?? [];
$groups = is_array($d['rows'] ?? null) ? $d['rows'] : [];
} else {
$errors[] = $r['error'] ?? 'Gagal memuat grup';
}
$pegawaiRows = $this->fetchPegawaiRowsForSelect($errors);
return view('admin/panel/user_create', [
'groups' => $groups,
'pegawai_rows' => $pegawaiRows,
'errors' => $errors,
]);
}
public function userStore(): ResponseInterface
{
if (($deny = $this->enforceAccess('panel')) !== null) {
return $deny;
}
$r = $this->apiAdminPost('panel/users/create', $this->request->getPost());
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
return redirect()->to(site_url('admin/panel/users'))->with('message', (string) ($r['json']['pesan'] ?? 'OK'));
}
$msg = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
return redirect()->to(site_url('admin/panel/users/create'))->withInput()->with('error', $msg);
}
public function userEdit(int $id): ResponseInterface|string
{
if (($deny = $this->enforceAccess('panel')) !== null) {
return $deny;
}
$errors = [];
$user = null;
$r = $this->apiAdminGet('panel/users/' . $id);
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$d = $r['json']['data'] ?? null;
$user = is_array($d) ? $d : null;
} else {
$errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal memuat pengguna') : 'Gagal memuat pengguna');
}
$groups = [];
$gr = $this->apiAdminGet('panel/groups');
if ($gr['transport_ok'] && ApiClient::isSuccess($gr['json'])) {
$gd = $gr['json']['data'] ?? [];
$groups = is_array($gd['rows'] ?? null) ? $gd['rows'] : [];
} else {
$errors[] = $gr['error'] ?? 'Gagal memuat grup';
}
$pegawaiRows = $this->fetchPegawaiRowsForSelect($errors);
return view('admin/panel/user_edit', [
'id' => $id,
'user' => $user,
'groups' => $groups,
'pegawai_rows' => $pegawaiRows,
'errors' => $errors,
]);
}
public function userUpdate(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('panel')) !== null) {
return $deny;
}
$r = $this->apiAdminPost('panel/users/update/' . $id, $this->request->getPost());
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
return redirect()->to(site_url('admin/panel/users'))->with('message', (string) ($r['json']['pesan'] ?? 'OK'));
}
$msg = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
return redirect()->to(site_url('admin/panel/users/edit/' . $id))->withInput()->with('error', $msg);
}
public function userReset(int $id): ResponseInterface|string
{
if (($deny = $this->enforceAccess('panel')) !== null) {
return $deny;
}
return view('admin/panel/user_reset', ['id' => $id]);
}
public function userResetPassword(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('panel')) !== null) {
return $deny;
}
$r = $this->apiAdminPost('panel/users/reset_password/' . $id, $this->request->getPost());
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
return redirect()->to(site_url('admin/panel/users'))->with('message', (string) ($r['json']['pesan'] ?? 'OK'));
}
$msg = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
return redirect()->to(site_url('admin/panel/users/reset/' . $id))->withInput()->with('error', $msg);
}
/**
* Gabungkan semua halaman `GET api/admin/pegawai` — satu request cuma mengembalikan `per_page` baris.
*
* @param list<string> $errors
*
* @return list<array<string, mixed>>
*/
private function fetchPegawaiRowsForSelect(array &$errors): array
{
$byId = [];
$page = 1;
$maxPage = 80;
while ($page <= $maxPage) {
$pr = $this->apiAdminGet('pegawai', [
'page' => (string) $page,
'per_page' => '500',
'q' => '',
]);
if (! $pr['transport_ok'] || ! ApiClient::isSuccess($pr['json'])) {
if ($page === 1) {
$errors[] = $pr['error'] ?? (is_array($pr['json']) ? (string) ($pr['json']['pesan'] ?? 'Gagal memuat daftar pegawai') : 'Gagal memuat daftar pegawai');
}
break;
}
$pd = $pr['json']['data'] ?? [];
$chunk = is_array($pd['rows'] ?? null) ? $pd['rows'] : [];
foreach ($chunk as $row) {
if (! is_array($row)) {
continue;
}
$pid = (int) ($row['id_pegawai'] ?? 0);
if ($pid > 0) {
$byId[$pid] = $row;
}
}
$totalPage = (int) ($pd['total_page'] ?? 1);
if ($page >= $totalPage || $chunk === []) {
break;
}
$page++;
}
$out = array_values($byId);
usort($out, static function (array $a, array $b): int {
return strcasecmp((string) ($a['nama_lengkap'] ?? ''), (string) ($b['nama_lengkap'] ?? ''));
});
return $out;
}
}

View File

@@ -0,0 +1,288 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Admin;
use App\Services\ApiClient;
use CodeIgniter\HTTP\ResponseInterface;
/**
* CRUD pegawai lewat API `/api/admin/pegawai/*` (tanpa query DB di controller).
*/
class Pegawai extends BaseAdminController
{
public function index(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('pegawai')) !== null) {
return $deny;
}
$page = max(1, (int) ($this->request->getGet('page') ?? 1));
$q = (string) ($this->request->getGet('q') ?? '');
$errors = [];
$payload = null;
$r = $this->apiAdminGet('pegawai', [
'page' => (string) $page,
'per_page' => '20',
'q' => $q,
]);
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$payload = $r['json']['data'] ?? null;
} else {
$errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal memuat daftar pegawai') : 'Gagal memuat daftar pegawai');
}
return view('admin/pegawai/index', [
'payload' => $payload,
'errors' => $errors,
'q' => $q,
'page' => $page,
]);
}
public function create(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('pegawai_tambah')) !== null) {
return $deny;
}
$refs = $this->loadReferences();
return view('admin/pegawai/form', [
'mode' => 'create',
'row' => null,
'refs' => $refs['data'],
'errors' => $refs['errors'],
'apiError' => null,
]);
}
public function store(): ResponseInterface
{
if (($deny = $this->enforceAccess('pegawai_tambah')) !== null) {
return $deny;
}
$post = $this->sanitizePegawaiPost($this->request->getPost() ?? []);
if (($err = $this->mergePegawaiPhotoIntoPost($post, null)) !== null) {
return redirect()->back()->withInput()->with('error', $err);
}
$res = $this->apiAdminPost('pegawai/create', $post);
if ($res['transport_ok'] && ApiClient::isSuccess($res['json'])) {
return redirect()->to(site_url('admin/pegawai'))->with('message', (string) ($res['json']['pesan'] ?? 'Data berhasil disimpan'));
}
$msg = is_array($res['json']) ? (string) ($res['json']['pesan'] ?? 'Gagal menyimpan') : ($res['error'] ?? 'Gagal menyimpan');
return redirect()->back()->withInput()->with('error', $msg);
}
public function edit(int $id): ResponseInterface|string
{
if (($deny = $this->enforceAccess('pegawai')) !== null) {
return $deny;
}
$refs = $this->loadReferences();
$row = null;
$err = $refs['errors'];
$r = $this->apiAdminGet('pegawai/' . $id);
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$row = $r['json']['data'] ?? null;
} else {
$err[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal memuat pegawai') : 'Gagal memuat pegawai');
}
return view('admin/pegawai/form', [
'mode' => 'edit',
'row' => is_array($row) ? $row : null,
'refs' => $refs['data'],
'errors' => $err,
'apiError' => null,
]);
}
public function update(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('pegawai')) !== null) {
return $deny;
}
$post = $this->sanitizePegawaiPost($this->request->getPost() ?? []);
$post['id_pegawai'] = $id;
$photoExisting = (string) ($this->request->getPost('photo_existing') ?? '');
if (($err = $this->mergePegawaiPhotoIntoPost($post, $photoExisting)) !== null) {
return redirect()->back()->withInput()->with('error', $err);
}
$res = $this->apiAdminPost('pegawai/update', $post);
if ($res['transport_ok'] && ApiClient::isSuccess($res['json'])) {
return redirect()->to(site_url('admin/pegawai'))->with('message', (string) ($res['json']['pesan'] ?? 'Data berhasil diperbarui'));
}
$msg = is_array($res['json']) ? (string) ($res['json']['pesan'] ?? 'Gagal memperbarui') : ($res['error'] ?? 'Gagal memperbarui');
return redirect()->back()->withInput()->with('error', $msg);
}
public function delete(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('pegawai')) !== null) {
return $deny;
}
$res = $this->apiAdminPost('pegawai/delete', ['id_pegawai' => (string) $id]);
if ($res['transport_ok'] && ApiClient::isSuccess($res['json'])) {
return redirect()->to(site_url('admin/pegawai'))->with('message', (string) ($res['json']['pesan'] ?? 'Terhapus'));
}
$msg = is_array($res['json']) ? (string) ($res['json']['pesan'] ?? 'Gagal menghapus') : ($res['error'] ?? 'Gagal menghapus');
return redirect()->back()->with('error', $msg);
}
public function reset(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('pegawai')) !== null) {
return $deny;
}
$res = $this->apiAdminPost('pegawai/reset_password', ['id_pegawai' => (string) $id]);
if ($res['transport_ok'] && ApiClient::isSuccess($res['json'])) {
return redirect()->to(site_url('admin/pegawai'))->with('message', (string) ($res['json']['pesan'] ?? 'Password direset'));
}
$msg = is_array($res['json']) ? (string) ($res['json']['pesan'] ?? 'Gagal reset') : ($res['error'] ?? 'Gagal reset');
return redirect()->back()->with('error', $msg);
}
/**
* @return array{data: array<string, mixed>|null, errors: list<string>}
*/
private function loadReferences(): array
{
$errors = [];
$data = null;
$r = $this->apiAdminGet('references');
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$data = is_array($r['json']['data'] ?? null) ? $r['json']['data'] : null;
} else {
$errors[] = $r['error'] ?? 'Referensi jabatan/unit tidak dapat dimuat.';
}
return ['data' => $data, 'errors' => $errors];
}
/**
* @param array<string, mixed> $post
*
* @return array<string, scalar|null>
*/
private function sanitizePegawaiPost(array $post): array
{
$out = [];
foreach ($post as $k => $v) {
if (! is_scalar($v) && $v !== null) {
continue;
}
$key = (string) $k;
if (in_array($key, ['nip', 'nama_lengkap', 'jenis_kelamin', 'tempat_lahir', 'tanggal_lahir', 'email', 'jabatan', 'unit_kerja', 'golongan_pekerjaan', 'kantor', 'status_kepegawaian', 'tanggal_bergabung', 'jadwal', 'super_akses', 'username', 'password', 'photo'], true)) {
$out[$key] = $v;
}
}
foreach (['jabatan', 'unit_kerja', 'golongan_pekerjaan', 'kantor', 'jadwal'] as $intKey) {
if (isset($out[$intKey]) && $out[$intKey] !== '' && $out[$intKey] !== null) {
$out[$intKey] = (int) $out[$intKey];
}
}
return $out;
}
/**
* Sama dengan aplikasi mobile: `public/assets/uploads/pengguna/`.
*/
private function pegawaiPhotoUploadDir(): string
{
$base = FCPATH . 'assets' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'pengguna';
if (! is_dir($base)) {
mkdir($base, 0755, true);
}
return $base;
}
/**
* Unggah file ke folder pengguna atau pakai nama file manual. Mengisi `$post['photo']`.
*
* @param array<string, scalar|null> $post
*
* @return string|null pesan error, atau null jika OK
*/
private function mergePegawaiPhotoIntoPost(array &$post, ?string $photoExistingFromDb): ?string
{
$file = $this->request->getFile('photo_file');
if ($file !== null && $file->getError() !== UPLOAD_ERR_NO_FILE) {
if (! $file->isValid()) {
return 'Unggah foto tidak valid.';
}
$mime = (string) $file->getMimeType();
$allowedMime = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (! in_array($mime, $allowedMime, true)) {
return 'Format foto harus JPG, PNG, GIF, atau WebP.';
}
if ($file->getSize() > 2_097_152) {
return 'Ukuran foto maksimal 2 MB.';
}
$ext = strtolower((string) ($file->guessExtension() ?: $file->getClientExtension()));
if (! in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp'], true)) {
return 'Ekstensi foto tidak didukung.';
}
$dir = $this->pegawaiPhotoUploadDir();
$rawName = pathinfo($file->getClientName(), PATHINFO_FILENAME);
$safeOriginal = preg_replace('/[^A-Za-z0-9._-]+/', '_', (string) $rawName) ?: 'photo';
$safeOriginal = substr($safeOriginal, 0, 80);
$filename = uniqid((string) mt_rand(), true) . '-' . $safeOriginal . '.' . $ext;
if (! $file->move($dir, $filename, true)) {
return 'Gagal menyimpan file foto ke server.';
}
$old = $photoExistingFromDb !== null ? trim($photoExistingFromDb) : '';
if ($old !== '' && $old !== '-' && $old !== $filename) {
$oldPath = $dir . DIRECTORY_SEPARATOR . basename(str_replace('\\', '/', $old));
if (is_file($oldPath)) {
@unlink($oldPath);
}
}
$post['photo'] = $filename;
return null;
}
$manual = isset($post['photo']) ? trim((string) $post['photo']) : '';
if ($manual === '' || $manual === '-') {
$post['photo'] = '';
return null;
}
$base = basename(str_replace('\\', '/', $manual));
if (! preg_match('/^[A-Za-z0-9._-]+$/', $base)) {
return 'Nama file foto hanya boleh huruf, angka, titik, garis bawah, dan tanda hubung (atau unggah file).';
}
$post['photo'] = substr($base, 0, 255);
return null;
}
}

View File

@@ -0,0 +1,645 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Admin;
use App\Services\ApiClient;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\HTTP\ResponseInterface;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
/**
* Daftar & detail presensi lewat `/api/admin/presensi*`.
*/
class Presensi extends BaseAdminController
{
public function index(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('presensi')) !== null) {
return $deny;
}
$today = date('Y-m-d');
$dari = (string) ($this->request->getGet('tanggal_dari') ?? $today);
$sampai = (string) ($this->request->getGet('tanggal_sampai') ?? $today);
$page = max(1, (int) ($this->request->getGet('page') ?? 1));
$q = (string) ($this->request->getGet('q') ?? '');
$errors = [];
$payload = null;
$r = $this->apiAdminGet('presensi', [
'tanggal_dari' => $dari,
'tanggal_sampai' => $sampai,
'page' => (string) $page,
'per_page' => '30',
'q' => $q,
]);
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$payload = $r['json']['data'] ?? null;
} else {
$errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal memuat presensi') : 'Gagal memuat presensi');
}
return view('admin/presensi/index', [
'payload' => $payload,
'errors' => $errors,
'dari' => $dari,
'sampai' => $sampai,
'page' => $page,
'q' => $q,
]);
}
/**
* Ambil semua baris presensi untuk ekspor (sama dengan filter list; maks. 100 halaman × 200 baris).
*
* @return array{ok: true, rows: list<array<string, mixed>>, dari: string, sampai: string, q: string}|array{ok: false, error: string, dari: string, sampai: string, q: string}
*/
private function fetchPresensiExportRows(): array
{
$today = date('Y-m-d');
$dari = (string) ($this->request->getGet('tanggal_dari') ?? $today);
$sampai = (string) ($this->request->getGet('tanggal_sampai') ?? $today);
$q = (string) ($this->request->getGet('q') ?? '');
$per = 200;
$maxPg = 100;
$allRows = [];
$totalPage = 1;
for ($page = 1; $page <= $totalPage && $page <= $maxPg; $page++) {
$r = $this->apiAdminGet('presensi', [
'tanggal_dari' => $dari,
'tanggal_sampai' => $sampai,
'page' => (string) $page,
'per_page' => (string) $per,
'q' => $q,
]);
if (! $r['transport_ok'] || ! ApiClient::isSuccess($r['json'])) {
$msg = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal mengekspor') : 'Gagal mengekspor');
return ['ok' => false, 'error' => $msg, 'dari' => $dari, 'sampai' => $sampai, 'q' => $q];
}
$payload = $r['json']['data'] ?? [];
$rows = is_array($payload['rows'] ?? null) ? $payload['rows'] : [];
if ($page === 1) {
$totalPage = max(1, min($maxPg, (int) ($payload['total_page'] ?? 1)));
}
$allRows = array_merge($allRows, $rows);
}
return ['ok' => true, 'rows' => $allRows, 'dari' => $dari, 'sampai' => $sampai, 'q' => $q];
}
/**
* Unduh CSV semua baris presensi untuk filter yang sama (paginasi digabung, maks. 100 halaman × 200 baris).
*/
public function exportCsv(): ResponseInterface
{
if (($deny = $this->enforceAccess('presensi')) !== null) {
return $deny;
}
$fetched = $this->fetchPresensiExportRows();
if (! $fetched['ok']) {
return redirect()->to(site_url('admin/presensi?' . http_build_query(array_filter([
'tanggal_dari' => $fetched['dari'],
'tanggal_sampai' => $fetched['sampai'],
'q' => $fetched['q'],
]))))->with('error', $fetched['error']);
}
$allRows = $fetched['rows'];
$dari = $fetched['dari'];
$sampai = $fetched['sampai'];
$fh = fopen('php://memory', 'r+b');
if ($fh === false) {
return redirect()->to(site_url('admin/presensi'))->with('error', 'Gagal membuat file CSV.');
}
fwrite($fh, "\xEF\xBB\xBF");
fputcsv($fh, [
'id_presensi',
'tanggal',
'nama_lengkap',
'nip',
'status',
'jam_masuk',
'ket_masuk',
'jam_pulang',
'ket_pulang',
'istirahat',
]);
foreach ($allRows as $pr) {
if (! is_array($pr)) {
continue;
}
$jm = $pr['jam_masuk'] ?? null;
$jp = $pr['jam_pulang'] ?? null;
$mi = $pr['mulai_istirahat'] ?? null;
$bi = $pr['beres_istirahat'] ?? null;
$ist = '';
if (! empty($mi) || ! empty($bi)) {
$ist = (empty($mi) ? '—' : self::formatTimeForCsv((string) $mi)) . ' → ' . (empty($bi) ? '—' : self::formatTimeForCsv((string) $bi));
}
fputcsv($fh, [
(string) ($pr['id_presensi'] ?? ''),
(string) ($pr['tanggal'] ?? ''),
(string) ($pr['nama_lengkap'] ?? ''),
(string) ($pr['nip'] ?? ''),
self::presensiStatusLabelForCsv($pr),
self::formatTimeForCsv($jm !== null ? (string) $jm : ''),
(string) ($pr['ket_masuk'] ?? ''),
self::formatTimeForCsv($jp !== null ? (string) $jp : ''),
(string) ($pr['ket_pulang'] ?? ''),
$ist,
]);
}
rewind($fh);
$csv = stream_get_contents($fh) ?: '';
fclose($fh);
$fn = 'presensi_' . preg_replace('/[^0-9-]/', '', $dari) . '_' . preg_replace('/[^0-9-]/', '', $sampai) . '_' . date('His') . '.csv';
return $this->response
->setHeader('Content-Type', 'text/csv; charset=UTF-8')
->setHeader('Content-Disposition', 'attachment; filename="' . str_replace(['"', "\r", "\n"], '', $fn) . '"')
->setBody($csv);
}
/**
* Unduh Excel (.xlsx) dengan kolom rapi: header tebal, filter, lebar kolom, teks ket. dibungkus.
*/
public function exportXlsx(): ResponseInterface
{
if (($deny = $this->enforceAccess('presensi')) !== null) {
return $deny;
}
$fetched = $this->fetchPresensiExportRows();
if (! $fetched['ok']) {
return redirect()->to(site_url('admin/presensi?' . http_build_query(array_filter([
'tanggal_dari' => $fetched['dari'],
'tanggal_sampai' => $fetched['sampai'],
'q' => $fetched['q'],
]))))->with('error', $fetched['error']);
}
$allRows = $fetched['rows'];
$dari = $fetched['dari'];
$sampai = $fetched['sampai'];
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Presensi');
$headers = [
'ID presensi',
'Tanggal',
'Nama lengkap',
'NIP',
'Status',
'Jam masuk',
'Ket. masuk',
'Jam pulang',
'Ket. pulang',
'Istirahat',
];
foreach ($headers as $i => $h) {
$sheet->setCellValue(Coordinate::stringFromColumnIndex($i + 1) . '1', $h);
}
$headerStyle = [
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
'fill' => [
'fillType' => Fill::FILL_SOLID,
'startColor' => ['rgb' => '1F4E79'],
],
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
'vertical' => Alignment::VERTICAL_CENTER,
],
'borders' => [
'allBorders' => ['borderStyle' => Border::BORDER_THIN, 'color' => ['rgb' => 'CCCCCC']],
],
];
$sheet->getStyle('A1:J1')->applyFromArray($headerStyle);
$sheet->getRowDimension(1)->setRowHeight(22);
$rowNum = 2;
foreach ($allRows as $pr) {
if (! is_array($pr)) {
continue;
}
$jm = $pr['jam_masuk'] ?? null;
$jp = $pr['jam_pulang'] ?? null;
$mi = $pr['mulai_istirahat'] ?? null;
$bi = $pr['beres_istirahat'] ?? null;
$ist = '';
if (! empty($mi) || ! empty($bi)) {
$ist = (empty($mi) ? '—' : self::formatTimeForCsv((string) $mi)) . ' → ' . (empty($bi) ? '—' : self::formatTimeForCsv((string) $bi));
}
$sheet->setCellValue('A' . $rowNum, (string) ($pr['id_presensi'] ?? ''));
$sheet->setCellValue('B' . $rowNum, (string) ($pr['tanggal'] ?? ''));
$sheet->setCellValue('C' . $rowNum, (string) ($pr['nama_lengkap'] ?? ''));
$sheet->setCellValue('D' . $rowNum, (string) ($pr['nip'] ?? ''));
$sheet->setCellValue('E' . $rowNum, self::presensiStatusLabelForCsv($pr));
$sheet->setCellValue('F' . $rowNum, self::formatTimeForCsv($jm !== null ? (string) $jm : ''));
$sheet->setCellValue('G' . $rowNum, (string) ($pr['ket_masuk'] ?? ''));
$sheet->setCellValue('H' . $rowNum, self::formatTimeForCsv($jp !== null ? (string) $jp : ''));
$sheet->setCellValue('I' . $rowNum, (string) ($pr['ket_pulang'] ?? ''));
$sheet->setCellValue('J' . $rowNum, $ist);
$rowNum++;
}
$lastRow = max(2, $rowNum - 1);
if ($lastRow >= 2) {
$sheet->getStyle('A2:J' . $lastRow)->applyFromArray([
'borders' => [
'allBorders' => ['borderStyle' => Border::BORDER_THIN, 'color' => ['rgb' => 'DDDDDD']],
],
'alignment' => [
'vertical' => Alignment::VERTICAL_TOP,
],
]);
$sheet->getStyle('G2:G' . $lastRow)->getAlignment()->setWrapText(true);
$sheet->getStyle('I2:I' . $lastRow)->getAlignment()->setWrapText(true);
$sheet->getStyle('A2:A' . $lastRow)->getNumberFormat()->setFormatCode('@');
$sheet->getStyle('D2:D' . $lastRow)->getNumberFormat()->setFormatCode('@');
}
$sheet->freezePane('A2');
$sheet->setAutoFilter('A1:J1');
$sheet->getColumnDimension('A')->setWidth(14);
$sheet->getColumnDimension('B')->setWidth(12);
$sheet->getColumnDimension('C')->setWidth(28);
$sheet->getColumnDimension('D')->setWidth(18);
$sheet->getColumnDimension('E')->setWidth(14);
$sheet->getColumnDimension('F')->setWidth(11);
$sheet->getColumnDimension('G')->setWidth(36);
$sheet->getColumnDimension('H')->setWidth(11);
$sheet->getColumnDimension('I')->setWidth(36);
$sheet->getColumnDimension('J')->setWidth(22);
$tmp = tempnam(sys_get_temp_dir(), 'prxlsx');
if ($tmp === false) {
return redirect()->to(site_url('admin/presensi'))->with('error', 'Gagal membuat file Excel.');
}
try {
(new Xlsx($spreadsheet))->save($tmp);
} catch (\Throwable $e) {
@unlink($tmp);
log_message('error', 'exportXlsx: {message}', ['message' => $e->getMessage()]);
return redirect()->to(site_url('admin/presensi?' . http_build_query(array_filter([
'tanggal_dari' => $dari,
'tanggal_sampai' => $sampai,
'q' => $fetched['q'],
]))))->with('error', 'Gagal menulis file Excel. Pastikan ekstensi PHP zip aktif.');
}
$binary = (string) file_get_contents($tmp);
@unlink($tmp);
$spreadsheet->disconnectWorksheets();
$fn = 'presensi_' . preg_replace('/[^0-9-]/', '', $dari) . '_' . preg_replace('/[^0-9-]/', '', $sampai) . '_' . date('His') . '.xlsx';
return $this->response
->setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
->setHeader('Content-Disposition', 'attachment; filename="' . str_replace(['"', "\r", "\n"], '', $fn) . '"')
->setBody($binary);
}
/**
* @param array<string, mixed> $pr
*/
private static function presensiStatusLabelForCsv(array $pr): string
{
$jm = $pr['jam_masuk'] ?? null;
$jp = $pr['jam_pulang'] ?? null;
$hadirMasuk = $jm !== null && $jm !== '';
$hadirPulang = $jp !== null && $jp !== '';
if ($hadirMasuk && $hadirPulang) {
return 'Lengkap';
}
if ($hadirMasuk || $hadirPulang) {
return 'Sebagian';
}
return 'Belum rekam';
}
private static function formatTimeForCsv(string $t): string
{
if ($t === '') {
return '';
}
$ts = strtotime($t);
return $ts ? date('H:i', $ts) : $t;
}
/**
* Layani foto absen masuk/pulang dari disk (public/assets/uploads/absen/…).
*/
public function foto(string $jenis, string $file): ResponseInterface
{
if (($deny = $this->enforceAccess('presensi')) !== null) {
return $deny;
}
$jenis = strtolower($jenis);
if ($jenis !== 'masuk' && $jenis !== 'pulang') {
throw PageNotFoundException::forPageNotFound();
}
$safe = basename(rawurldecode($file));
if ($safe === '' || $safe === '.' || $safe === '..') {
throw PageNotFoundException::forPageNotFound();
}
if (! preg_match('/^[A-Za-z0-9._-]+$/', $safe)) {
throw PageNotFoundException::forPageNotFound();
}
$path = FCPATH . 'assets' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'absen' . DIRECTORY_SEPARATOR . $jenis . DIRECTORY_SEPARATOR . $safe;
if (! is_file($path)) {
throw PageNotFoundException::forPageNotFound(
'Foto tidak ada di server. Salin folder absen/masuk dan absen/pulang dari CI3 ke: public/assets/uploads/absen/',
);
}
$ext = strtolower((string) pathinfo($safe, PATHINFO_EXTENSION));
$mime = match ($ext) {
'jpg', 'jpeg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'webp' => 'image/webp',
default => 'application/octet-stream',
};
$this->response->setHeader('Content-Type', $mime);
$this->response->setHeader('Content-Disposition', 'inline; filename="' . addcslashes($safe, '"\\') . '"');
return $this->response->setBody((string) file_get_contents($path));
}
public function detail(int $id): ResponseInterface|string
{
if (($deny = $this->enforceAccess('presensi')) !== null) {
return $deny;
}
$errors = [];
$row = null;
$r = $this->apiAdminGet('presensi/' . $id);
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$row = $r['json']['data'] ?? null;
} else {
$errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal memuat detail') : 'Gagal memuat detail');
}
return view('admin/presensi/detail', [
'row' => is_array($row) ? $row : null,
'errors' => $errors,
]);
}
public function lapangan(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('presensi')) !== null) {
return $deny;
}
$errors = [];
$payload = null;
$pegawai = [];
$r = $this->apiAdminGet('presensi/dilapangan');
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$payload = $r['json']['data'] ?? null;
} else {
$errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
}
$p = $this->apiAdminGet('pegawai', ['page' => '1', 'per_page' => '500', 'q' => '']);
if ($p['transport_ok'] && ApiClient::isSuccess($p['json'])) {
$d = $p['json']['data'] ?? [];
$pegawai = is_array($d['rows'] ?? null) ? $d['rows'] : [];
}
return view('admin/presensi/lapangan', [
'payload' => is_array($payload) ? $payload : null,
'pegawai' => $pegawai,
'errors' => $errors,
]);
}
public function lapanganSave(): ResponseInterface
{
if (($deny = $this->enforceAccess('presensi')) !== null) {
return $deny;
}
return $this->toolPost('presensi/dilapangan/save', 'admin/presensi/lapangan');
}
public function lapanganDelete(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('presensi')) !== null) {
return $deny;
}
return $this->toolPost('presensi/dilapangan/delete/' . $id, 'admin/presensi/lapangan', []);
}
public function lembur(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('presensi')) !== null) {
return $deny;
}
$errors = [];
$payload = null;
$pegawai = [];
$r = $this->apiAdminGet('presensi/lembur');
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$payload = $r['json']['data'] ?? null;
} else {
$errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
}
$p = $this->apiAdminGet('pegawai', ['page' => '1', 'per_page' => '500', 'q' => '']);
if ($p['transport_ok'] && ApiClient::isSuccess($p['json'])) {
$d = $p['json']['data'] ?? [];
$pegawai = is_array($d['rows'] ?? null) ? $d['rows'] : [];
}
return view('admin/presensi/lembur', [
'payload' => is_array($payload) ? $payload : null,
'pegawai' => $pegawai,
'errors' => $errors,
]);
}
public function lemburSave(): ResponseInterface
{
if (($deny = $this->enforceAccess('presensi')) !== null) {
return $deny;
}
return $this->toolPost('presensi/lembur/save', 'admin/presensi/lembur');
}
public function lemburDelete(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('presensi')) !== null) {
return $deny;
}
return $this->toolPost('presensi/lembur/delete/' . $id, 'admin/presensi/lembur', []);
}
public function libur(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('presensi_libur')) !== null) {
return $deny;
}
return $this->toolPage('presensi/libur', 'admin/presensi/libur', false);
}
public function liburSave(): ResponseInterface
{
if (($deny = $this->enforceAccess('presensi_libur')) !== null) {
return $deny;
}
return $this->toolPost('presensi/libur/save', 'admin/presensi/libur');
}
public function liburDelete(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('presensi_libur')) !== null) {
return $deny;
}
return $this->toolPost('presensi/libur/delete/' . $id, 'admin/presensi/libur', []);
}
public function jadwal(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('presensi_jadwal')) !== null) {
return $deny;
}
return $this->toolPage('presensi/jadwal', 'admin/presensi/jadwal', false);
}
public function jadwalSave(): ResponseInterface
{
if (($deny = $this->enforceAccess('presensi_jadwal')) !== null) {
return $deny;
}
return $this->toolPost('presensi/jadwal/save', 'admin/presensi/jadwal');
}
public function jadwalDelete(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('presensi_jadwal')) !== null) {
return $deny;
}
return $this->toolPost('presensi/jadwal/delete/' . $id, 'admin/presensi/jadwal', []);
}
public function aktivitas(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('presensi')) !== null) {
return $deny;
}
$page = max(1, (int) ($this->request->getGet('page') ?? 1));
$errors = [];
$payload = null;
$r = $this->apiAdminGet('presensi/aktivitas', ['page' => (string) $page, 'per_page' => '20']);
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$payload = $r['json']['data'] ?? null;
} else {
$errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
}
return view('admin/presensi/aktivitas', [
'payload' => is_array($payload) ? $payload : null,
'errors' => $errors,
'page' => $page,
]);
}
public function aktivitasDelete(int $id): ResponseInterface
{
if (($deny = $this->enforceAccess('presensi')) !== null) {
return $deny;
}
return $this->toolPost('presensi/aktivitas/delete/' . $id, 'admin/presensi/aktivitas', []);
}
/**
* @return ResponseInterface|string
*/
private function toolPage(string $apiPath, string $view, bool $loadRefs)
{
$errors = [];
$payload = null;
$refs = null;
$r = $this->apiAdminGet($apiPath);
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$payload = $r['json']['data'] ?? null;
} else {
$errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal memuat data') : 'Gagal memuat data');
}
if ($loadRefs) {
$ref = $this->apiAdminGet('references');
if ($ref['transport_ok'] && ApiClient::isSuccess($ref['json'])) {
$refs = $ref['json']['data'] ?? null;
}
}
return view($view, [
'payload' => is_array($payload) ? $payload : null,
'refs' => is_array($refs) ? $refs : null,
'errors' => $errors,
]);
}
/**
* @param array<string, scalar|null> $merge
*/
private function toolPost(string $apiPath, string $redirectPath, array $merge = []): ResponseInterface
{
$post = array_merge($this->request->getPost(), $merge);
$r = $this->apiAdminPost($apiPath, $post);
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
return redirect()->to(site_url($redirectPath))->with('message', (string) ($r['json']['pesan'] ?? 'OK'));
}
$msg = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
return redirect()->to(site_url($redirectPath))->with('error', $msg);
}
}

View File

@@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Admin;
use App\Services\Admin\AdminExtraApiService;
use App\Services\ApiClient;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Utilitas backup DB — file di <code>writable/admin_db_backup/</code>.
*/
class Util extends BaseAdminController
{
public function backup(): ResponseInterface|string
{
if (($deny = $this->enforceAccess('utilitas')) !== null) {
return $deny;
}
$errors = [];
$data = null;
$r = $this->apiAdminGet('backup');
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
$data = $r['json']['data'] ?? null;
} else {
$errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
}
return view('admin/util/backup', [
'payload' => is_array($data) ? $data : null,
'errors' => $errors,
]);
}
public function backupRun(): ResponseInterface
{
if (($deny = $this->enforceAccess('utilitas')) !== null) {
return $deny;
}
$post = $this->request->getPost();
$r = $this->apiAdminPost('backup/run', $post);
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
return redirect()->to(site_url('admin/util/backup'))->with('message', (string) ($r['json']['pesan'] ?? 'Backup OK'));
}
$msg = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
return redirect()->to(site_url('admin/util/backup'))->with('error', $msg);
}
public function backupDelete(string $file): ResponseInterface
{
if (($deny = $this->enforceAccess('utilitas')) !== null) {
return $deny;
}
$r = $this->apiAdminPost('backup/delete/' . rawurlencode($file), []);
if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
return redirect()->to(site_url('admin/util/backup'))->with('message', 'File dihapus');
}
$msg = $r['error'] ?? 'Gagal hapus';
return redirect()->to(site_url('admin/util/backup'))->with('error', $msg);
}
public function backupDownload(string $file): ResponseInterface
{
if (($deny = $this->enforceAccess('utilitas')) !== null) {
return $deny;
}
$extra = new AdminExtraApiService();
$path = $extra->backupFilePath($file);
if ($path === null) {
return redirect()->to(site_url('admin/util/backup'))->with('error', 'File tidak ditemukan');
}
$dl = $this->response->download($path, null);
if ($dl === null) {
return redirect()->to(site_url('admin/util/backup'))->with('error', 'Gagal menyiapkan unduhan');
}
return $dl->setFileName(basename($path));
}
}

View File

@@ -0,0 +1,269 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Api\Admin;
use App\Controllers\BaseController;
use App\Services\Admin\AdminApiService;
use App\Services\Admin\AdminExtraApiService;
use App\Services\AdminAuditService;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
/**
* Dasar API `/api/admin/*`: wajib **sesi panel admin** + token yang sama dengan sesi;
* RBAC per fitur (`canAccess`). Tanpa cookie sesi, panggilan hanya dengan `?token=` ditolak.
*
* Audit: setelah otorisasi sukses, controller anak memanggil {@see auditAuthorized()}.
* Percobaan ditolak dicatat ke DB + `log_message`.
*/
abstract class BaseAdminApiController extends BaseController
{
protected AdminApiService $adminApi;
protected AdminExtraApiService $adminExtra;
private AdminAuditService $audit;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger): void
{
parent::initController($request, $response, $logger);
helper('rbac');
$this->adminApi = new AdminApiService();
$this->adminExtra = new AdminExtraApiService();
$this->audit = new AdminAuditService();
}
/**
* @param array<string, mixed> $payload
*/
protected function auditAuthorized(string $action, array $actor, array $payload = []): void
{
$payload['actor'] = $this->actorAuditSummary($actor);
$this->audit->log($action, $payload);
}
/**
* @param array<string, mixed> $actor
*
* @return array<string, mixed>
*/
private function actorAuditSummary(array $actor): array
{
return [
'id_pegawai' => $actor['id_pegawai'] ?? null,
'nip' => $actor['nip'] ?? null,
'nama_lengkap' => $actor['nama_lengkap'] ?? null,
];
}
/**
* Ringkasan GET/POST untuk payload audit (dibatasi ukuran).
*
* @return array<string, mixed>
*/
protected function auditRequestParams(): array
{
$get = $this->request->getGet();
$post = $this->request->getPost();
return [
'query' => is_array($get) ? $this->truncateParamMap($get, 40) : [],
'post' => is_array($post) ? $this->truncateParamMap($post, 40) : [],
];
}
/**
* @param array<string, mixed> $map
*
* @return array<string, mixed>
*/
private function truncateParamMap(array $map, int $maxKeys): array
{
$i = 0;
$out = [];
foreach ($map as $k => $v) {
if ($i++ >= $maxKeys) {
$out['_truncated'] = true;
break;
}
if (is_scalar($v) || $v === null) {
$out[(string) $k] = $v;
} elseif (is_array($v)) {
$out[(string) $k] = '[array]';
}
}
return $out;
}
/**
* @param array<string, mixed> $payload
*/
protected function respond(array $payload, int $code = 200): ResponseInterface
{
return $this->response->setStatusCode($code)->setJSON($payload);
}
protected function extractToken(): string
{
$t = $this->request->getGet('token')
?? $this->request->getPost('token')
?? $this->request->getHeaderLine('X-Admin-Token');
return is_string($t) ? trim($t) : '';
}
/**
* Sesi admin panel aktif + token permintaan sama dengan `admin_mobile_token` di sesi.
*
* @return array{actor: array<string, mixed>|null, response: null}|array{actor: null, response: ResponseInterface}
*/
protected function requireAdminSessionBoundToken(): array
{
$sess = session();
$sessTok = $sess->get('admin_mobile_token');
if (! is_string($sessTok) || $sessTok === '') {
$this->logAdminSecurityDenied('no_admin_session', 'unauthorized');
return [
'actor' => null,
'response' => $this->respond(['status' => 0, 'pesan' => 'Unauthorized'], 401),
];
}
$reqTok = $this->extractToken();
if ($reqTok === '' || $reqTok !== $sessTok) {
$this->logAdminSecurityDenied('token_not_bound_to_session', 'unauthorized');
return [
'actor' => null,
'response' => $this->respond(['status' => 0, 'pesan' => 'Unauthorized'], 401),
];
}
$actor = $this->adminApi->actorFromToken($reqTok);
if ($actor === null) {
$this->logAdminSecurityDenied('invalid_token_actor', 'unauthorized');
return [
'actor' => null,
'response' => $this->respond(['status' => 0, 'pesan' => 'Token tidak valid'], 403),
];
}
return ['actor' => $actor, 'response' => null];
}
/**
* RBAC fitur — memakai `admin_ion_groups` + `Config\AdminAccess` (sama lapisan web).
*/
protected function requireAdminFeature(string $feature): ?ResponseInterface
{
if (canAccess($feature)) {
return null;
}
$this->logAdminSecurityDenied('forbidden_feature:' . $feature, 'forbidden');
return $this->respond(['status' => 0, 'pesan' => 'Forbidden'], 403);
}
/**
* Gabungan autentikasi sesi + RBAC satu pintu untuk endpoint admin API.
*
* @return array{actor: array<string, mixed>|null, response: null}|array{actor: null, response: ResponseInterface}
*/
protected function requireAdminApiAccess(string $feature): array
{
$auth = $this->requireAdminSessionBoundToken();
if ($auth['response'] !== null) {
return $auth;
}
$deny = $this->requireAdminFeature($feature);
if ($deny !== null) {
return ['actor' => $auth['actor'], 'response' => $deny];
}
return ['actor' => $auth['actor'], 'response' => null];
}
/**
* Filter cabang untuk grup Ion `supervisor`: data pegawai/cuti/presensi dibatasi ke `pegawai.kantor`
* yang sama dengan baris pegawai pemegang token (bukan dari jabatan).
*
* @return array{scoped: bool, kantor_id: int|null} scoped=true & kantor_id=null → pegawai supervisor belum punya kantor
*/
protected function cabangScopeFromActor(?array $actor): array
{
if ($actor === null || ! rbac_enforce_ion()) {
return ['scoped' => false, 'kantor_id' => null];
}
if (hasRole('webmaster') || hasRole('hrd')) {
return ['scoped' => false, 'kantor_id' => null];
}
if (! hasRole('supervisor')) {
return ['scoped' => false, 'kantor_id' => null];
}
$kid = (int) ($actor['kantor'] ?? 0);
if ($kid <= 0) {
return ['scoped' => true, 'kantor_id' => null];
}
return ['scoped' => true, 'kantor_id' => $kid];
}
/**
* Supervisor wajib punya `kantor` pada baris pegawai (token) agar scope cabang terdefinisi.
*/
protected function denyIfSupervisorCabangInvalid(array $scope): ?ResponseInterface
{
if ($scope['scoped'] && $scope['kantor_id'] === null) {
return $this->respond([
'status' => 0,
'pesan' => 'Akun supervisor belum memiliki cabang (kantor) pada data pegawai. Hubungi HRD untuk mengisi kolom kantor.',
], 403);
}
return null;
}
/** @return int|null null = tanpa filter cabang */
protected function cabangKantorIdForQueries(array $scope): ?int
{
return $scope['scoped'] ? $scope['kantor_id'] : null;
}
/**
* Setelah {@see requireAdminApiAccess()} sukses: validasi kantor supervisor & siapkan filter cabang.
*
* @return array{kid: int|null, response: ResponseInterface|null}
*/
protected function cabangKantorAfterAuth(?array $actor): array
{
$scope = $this->cabangScopeFromActor($actor);
if (($deny = $this->denyIfSupervisorCabangInvalid($scope)) !== null) {
return ['kid' => null, 'response' => $deny];
}
return ['kid' => $this->cabangKantorIdForQueries($scope), 'response' => null];
}
private function logAdminSecurityDenied(string $reason, string $outcome): void
{
$ip = $this->request->getIPAddress();
$path = $this->request->getUri()->getPath();
$when = date('c');
log_message('warning', "[api/admin] denied={$reason} outcome={$outcome} ip={$ip} path={$path} at={$when}");
$action = $outcome === 'forbidden' ? 'api.admin.security.forbidden' : 'api.admin.security.unauthorized';
$this->audit->log($action, [
'reason' => $reason,
'__outcome' => $outcome,
]);
}
}

View File

@@ -0,0 +1,189 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Api\Admin;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Master data perusahaan (kantor, unit kerja, golongan, jabatan, berita).
*/
class CompanyDataApiController extends BaseAdminApiController
{
public function kantor(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('perusahaan');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.company.kantor.list', $auth['actor'], ['request' => $this->auditRequestParams()]);
return $this->respond($this->adminExtra->kantorList());
}
public function kantorSave(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('perusahaan');
if ($auth['response'] !== null) {
return $auth['response'];
}
$post = $this->request->getPost();
$id = (int) ($post['id_kantor'] ?? 0);
$this->auditAuthorized('api.admin.company.kantor.save', $auth['actor'], ['id_kantor' => $id ?: null]);
return $this->respond($this->adminExtra->kantorSave($post, $id > 0 ? $id : null));
}
public function kantorDelete(int $id): ResponseInterface
{
$auth = $this->requireAdminApiAccess('perusahaan');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.company.kantor.delete', $auth['actor'], ['id_kantor' => $id]);
return $this->respond($this->adminExtra->kantorDelete($id));
}
public function unitKerja(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('perusahaan');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.company.unit_kerja.list', $auth['actor'], ['request' => $this->auditRequestParams()]);
return $this->respond($this->adminExtra->unitKerjaList());
}
public function unitKerjaSave(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('perusahaan');
if ($auth['response'] !== null) {
return $auth['response'];
}
$post = $this->request->getPost();
$id = (int) ($post['id_unit_kerja'] ?? 0);
$this->auditAuthorized('api.admin.company.unit_kerja.save', $auth['actor'], ['id' => $id ?: null]);
return $this->respond($this->adminExtra->unitKerjaSave($post, $id > 0 ? $id : null));
}
public function unitKerjaDelete(int $id): ResponseInterface
{
$auth = $this->requireAdminApiAccess('perusahaan');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.company.unit_kerja.delete', $auth['actor'], ['id' => $id]);
return $this->respond($this->adminExtra->unitKerjaDelete($id));
}
public function golongan(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('perusahaan');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.company.golongan.list', $auth['actor'], ['request' => $this->auditRequestParams()]);
return $this->respond($this->adminExtra->golonganList());
}
public function golonganSave(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('perusahaan');
if ($auth['response'] !== null) {
return $auth['response'];
}
$post = $this->request->getPost();
$id = (int) ($post['id_golongan'] ?? 0);
$this->auditAuthorized('api.admin.company.golongan.save', $auth['actor'], ['id' => $id ?: null]);
return $this->respond($this->adminExtra->golonganSave($post, $id > 0 ? $id : null));
}
public function golonganDelete(int $id): ResponseInterface
{
$auth = $this->requireAdminApiAccess('perusahaan');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.company.golongan.delete', $auth['actor'], ['id' => $id]);
return $this->respond($this->adminExtra->golonganDelete($id));
}
public function jabatan(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('perusahaan');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.company.jabatan.list', $auth['actor'], ['request' => $this->auditRequestParams()]);
return $this->respond($this->adminExtra->jabatanList());
}
public function jabatanSave(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('perusahaan');
if ($auth['response'] !== null) {
return $auth['response'];
}
$post = $this->request->getPost();
$id = (int) ($post['id_jabatan'] ?? 0);
$this->auditAuthorized('api.admin.company.jabatan.save', $auth['actor'], ['id' => $id ?: null]);
return $this->respond($this->adminExtra->jabatanSave($post, $id > 0 ? $id : null));
}
public function jabatanDelete(int $id): ResponseInterface
{
$auth = $this->requireAdminApiAccess('perusahaan');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.company.jabatan.delete', $auth['actor'], ['id' => $id]);
return $this->respond($this->adminExtra->jabatanDelete($id));
}
public function berita(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('perusahaan');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.company.berita.list', $auth['actor'], ['request' => $this->auditRequestParams()]);
return $this->respond($this->adminExtra->beritaList());
}
public function beritaSave(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('perusahaan');
if ($auth['response'] !== null) {
return $auth['response'];
}
$post = $this->request->getPost();
$id = (int) ($post['id_berita'] ?? 0);
$this->auditAuthorized('api.admin.company.berita.save', $auth['actor'], ['id' => $id ?: null]);
return $this->respond($this->adminExtra->beritaSave($post, $id > 0 ? $id : null));
}
public function beritaDelete(int $id): ResponseInterface
{
$auth = $this->requireAdminApiAccess('perusahaan');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.company.berita.delete', $auth['actor'], ['id' => $id]);
return $this->respond($this->adminExtra->beritaDelete($id));
}
}

View File

@@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Api\Admin;
use CodeIgniter\HTTP\ResponseInterface;
class CutiController extends BaseAdminApiController
{
public function index(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('cuti');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$this->auditAuthorized('api.admin.cuti.index', $auth['actor'], [
'request' => $this->auditRequestParams(),
]);
$status = (string) ($this->request->getGet('status') ?? 'Waiting');
$page = max(1, (int) ($this->request->getGet('page') ?? 1));
$perPage = max(5, min(200, (int) ($this->request->getGet('per_page') ?? 30)));
return $this->respond($this->adminApi->cutiList($status, $page, $perPage, $cb['kid']));
}
public function show(?string $id = null): ResponseInterface
{
$auth = $this->requireAdminApiAccess('cuti');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$this->auditAuthorized('api.admin.cuti.show', $auth['actor'], [
'request' => $this->auditRequestParams(),
'id' => $id,
]);
$idInt = (int) ($id ?? 0);
if ($idInt <= 0) {
return $this->respond(['status' => 0, 'pesan' => 'ID tidak valid'], 400);
}
return $this->respond($this->adminApi->cutiShow($idInt, $cb['kid']));
}
public function approve(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('cuti');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$id = (int) ($this->request->getPost('id_cuti') ?? 0);
if ($id <= 0) {
return $this->respond(['status' => 0, 'pesan' => 'id_cuti wajib'], 400);
}
$this->auditAuthorized('api.admin.cuti.approve', $auth['actor'], [
'cuti' => ['id_cuti' => $id],
]);
return $this->respond($this->adminApi->cutiApprove($id, $cb['kid']));
}
public function reject(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('cuti');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$id = (int) ($this->request->getPost('id_cuti') ?? 0);
if ($id <= 0) {
return $this->respond(['status' => 0, 'pesan' => 'id_cuti wajib'], 400);
}
$alasan = (string) ($this->request->getPost('alasan_tolak') ?? '');
$this->auditAuthorized('api.admin.cuti.reject', $auth['actor'], [
'cuti' => [
'id_cuti' => $id,
'alasan_tolak' => function_exists('mb_substr') ? mb_substr($alasan, 0, 500) : substr($alasan, 0, 500),
],
]);
return $this->respond($this->adminApi->cutiReject($id, $alasan, $cb['kid']));
}
}

View File

@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Api\Admin;
use CodeIgniter\HTTP\ResponseInterface;
class DashboardController extends BaseAdminApiController
{
public function index(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('dashboard');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$this->auditAuthorized('api.admin.dashboard.index', $auth['actor'], [
'request' => $this->auditRequestParams(),
]);
$soloPegawaiId = null;
if (! rbac_enforce_ion()) {
$soloPegawaiId = (int) ($auth['actor']['id_pegawai'] ?? 0);
if ($soloPegawaiId <= 0) {
$soloPegawaiId = null;
}
}
return $this->respond($this->adminApi->dashboardHome($cb['kid'], $soloPegawaiId));
}
}

View File

@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Api\Admin;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Utilitas: daftar file backup SQL di writable, buat backup, hapus file.
*/
class DatabaseBackupApiController extends BaseAdminApiController
{
public function index(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('utilitas');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.backup.list', $auth['actor'], ['request' => $this->auditRequestParams()]);
return $this->respond($this->adminExtra->backupListFiles());
}
public function run(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('utilitas');
if ($auth['response'] !== null) {
return $auth['response'];
}
$also = (string) ($this->request->getPost('save_latest') ?? '') === '1';
$this->auditAuthorized('api.admin.backup.run', $auth['actor'], [
'save_latest' => $also,
'request' => $this->auditRequestParams(),
]);
return $this->respond($this->adminExtra->backupRun($also));
}
public function delete(string $file): ResponseInterface
{
$auth = $this->requireAdminApiAccess('utilitas');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.backup.delete', $auth['actor'], ['file' => $file]);
return $this->respond($this->adminExtra->backupDelete($file));
}
}

View File

@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Api\Admin;
use CodeIgniter\HTTP\ResponseInterface;
class LaporanController extends BaseAdminApiController
{
public function index(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('laporan');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$this->auditAuthorized('api.admin.laporan.index', $auth['actor'], [
'request' => $this->auditRequestParams(),
]);
$today = date('Y-m-d');
$dari = (string) ($this->request->getGet('dari') ?? $today);
$sampai = (string) ($this->request->getGet('sampai') ?? $today);
if (strtotime($dari) === false || strtotime($sampai) === false) {
return $this->respond(['status' => 0, 'pesan' => 'Format tanggal tidak valid'], 400);
}
if ($dari > $sampai) {
[$dari, $sampai] = [$sampai, $dari];
}
return $this->respond($this->adminApi->laporanSummary($dari, $sampai, $cb['kid']));
}
/**
* Laporan cuti rentang tanggal (parity CI3 laporan/fcuti — data tabel).
*/
public function cutiRentang(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('laporan');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$this->auditAuthorized('api.admin.laporan.cuti_rentang', $auth['actor'], [
'request' => $this->auditRequestParams(),
]);
$today = date('Y-m-d');
$dari = (string) ($this->request->getGet('dari') ?? $today);
$sampai = (string) ($this->request->getGet('sampai') ?? $today);
if (strtotime($dari) === false || strtotime($sampai) === false) {
return $this->respond(['status' => 0, 'pesan' => 'Format tanggal tidak valid'], 400);
}
if ($dari > $sampai) {
[$dari, $sampai] = [$sampai, $dari];
}
return $this->respond($this->adminExtra->laporanCutiRentang($dari, $sampai, $cb['kid']));
}
}

View File

@@ -0,0 +1,139 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Api\Admin;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Panel Ion Auth: daftar pengguna admin, grup, buat user, reset password.
*/
class PanelUsersApiController extends BaseAdminApiController
{
public function users(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('panel');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.panel.users.list', $auth['actor'], ['request' => $this->auditRequestParams()]);
return $this->respond($this->adminExtra->adminUsersList());
}
public function userShow(?string $id = null): ResponseInterface
{
$auth = $this->requireAdminApiAccess('panel');
if ($auth['response'] !== null) {
return $auth['response'];
}
$idInt = (int) ($id ?? 0);
if ($idInt <= 0) {
return $this->respond(['status' => 0, 'pesan' => 'ID tidak valid'], 400);
}
$this->auditAuthorized('api.admin.panel.users.show', $auth['actor'], [
'request' => $this->auditRequestParams(),
'user_id' => $idInt,
]);
return $this->respond($this->adminExtra->adminUserShow($idInt));
}
public function userUpdate(int $id): ResponseInterface
{
$auth = $this->requireAdminApiAccess('panel');
if ($auth['response'] !== null) {
return $auth['response'];
}
if ($id <= 0) {
return $this->respond(['status' => 0, 'pesan' => 'ID tidak valid'], 400);
}
$this->auditAuthorized('api.admin.panel.users.update', $auth['actor'], [
'user_id' => $id,
'request' => $this->auditRequestParams(),
]);
return $this->respond($this->adminExtra->adminUserUpdate($id, $this->request->getPost()));
}
public function groups(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('panel');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.panel.groups.list', $auth['actor'], ['request' => $this->auditRequestParams()]);
return $this->respond($this->adminExtra->adminGroupsList());
}
public function groupCreate(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('panel');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.panel.groups.create', $auth['actor'], ['request' => $this->auditRequestParams()]);
return $this->respond($this->adminExtra->adminGroupCreate($this->request->getPost()));
}
public function groupUpdate(int $id): ResponseInterface
{
$auth = $this->requireAdminApiAccess('panel');
if ($auth['response'] !== null) {
return $auth['response'];
}
if ($id <= 0) {
return $this->respond(['status' => 0, 'pesan' => 'ID grup tidak valid'], 400);
}
$this->auditAuthorized('api.admin.panel.groups.update', $auth['actor'], [
'group_id' => $id,
'request' => $this->auditRequestParams(),
]);
return $this->respond($this->adminExtra->adminGroupUpdate($id, $this->request->getPost()));
}
public function groupDelete(int $id): ResponseInterface
{
$auth = $this->requireAdminApiAccess('panel');
if ($auth['response'] !== null) {
return $auth['response'];
}
if ($id <= 0) {
return $this->respond(['status' => 0, 'pesan' => 'ID grup tidak valid'], 400);
}
$this->auditAuthorized('api.admin.panel.groups.delete', $auth['actor'], ['group_id' => $id]);
return $this->respond($this->adminExtra->adminGroupDelete($id));
}
public function userCreate(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('panel');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.panel.users.create', $auth['actor'], [
'request' => $this->auditRequestParams(),
]);
return $this->respond($this->adminExtra->adminUserCreate($this->request->getPost()));
}
public function userResetPassword(int $id): ResponseInterface
{
$auth = $this->requireAdminApiAccess('panel');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.panel.users.reset_password', $auth['actor'], [
'user_id' => $id,
'request' => $this->auditRequestParams(),
]);
return $this->respond($this->adminExtra->adminUserResetPassword($id, $this->request->getPost()));
}
}

View File

@@ -0,0 +1,164 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Api\Admin;
use CodeIgniter\HTTP\ResponseInterface;
class PegawaiController extends BaseAdminApiController
{
public function index(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('pegawai');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$this->auditAuthorized('api.admin.pegawai.index', $auth['actor'], [
'request' => $this->auditRequestParams(),
]);
$page = (int) ($this->request->getGet('page') ?? 1);
$perPage = (int) ($this->request->getGet('per_page') ?? 20);
$search = (string) ($this->request->getGet('q') ?? '');
return $this->respond($this->adminApi->pegawaiList($page, $perPage, $search, $cb['kid']));
}
public function show(?string $id = null): ResponseInterface
{
$auth = $this->requireAdminApiAccess('pegawai');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$this->auditAuthorized('api.admin.pegawai.show', $auth['actor'], [
'request' => $this->auditRequestParams(),
'id' => $id,
]);
$idInt = (int) ($id ?? 0);
if ($idInt <= 0) {
return $this->respond(['status' => 0, 'pesan' => 'ID tidak valid'], 400);
}
return $this->respond($this->adminApi->pegawaiShow($idInt, $cb['kid']));
}
public function create(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('pegawai_tambah');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$input = $this->normalizePegawaiInput($this->request->getPost());
$this->auditAuthorized('api.admin.pegawai.create', $auth['actor'], [
'pegawai' => $input,
]);
return $this->respond($this->adminApi->pegawaiCreate($input, $cb['kid']));
}
public function update(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('pegawai');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$id = (int) ($this->request->getPost('id_pegawai') ?? 0);
if ($id <= 0) {
return $this->respond(['status' => 0, 'pesan' => 'id_pegawai wajib'], 400);
}
$input = $this->normalizePegawaiInput($this->request->getPost());
$this->auditAuthorized('api.admin.pegawai.update', $auth['actor'], [
'pegawai' => array_merge(['id_pegawai' => $id], $input),
]);
return $this->respond($this->adminApi->pegawaiUpdate($id, $input, $cb['kid']));
}
public function delete(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('pegawai');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$id = (int) ($this->request->getPost('id_pegawai') ?? 0);
if ($id <= 0) {
return $this->respond(['status' => 0, 'pesan' => 'id_pegawai wajib'], 400);
}
$this->auditAuthorized('api.admin.pegawai.delete', $auth['actor'], [
'pegawai' => ['id_pegawai' => $id],
]);
return $this->respond($this->adminApi->pegawaiDelete($id, $cb['kid']));
}
public function resetPassword(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('pegawai');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$id = (int) ($this->request->getPost('id_pegawai') ?? 0);
if ($id <= 0) {
return $this->respond(['status' => 0, 'pesan' => 'id_pegawai wajib'], 400);
}
$this->auditAuthorized('api.admin.pegawai.reset_password', $auth['actor'], [
'pegawai' => ['id_pegawai' => $id],
]);
return $this->respond($this->adminApi->pegawaiResetPassword($id, $cb['kid']));
}
/**
* @param array<string, mixed> $post
*
* @return array<string, scalar|null>
*/
private function normalizePegawaiInput(array $post): array
{
$out = [];
foreach ($post as $k => $v) {
if (is_scalar($v) || $v === null) {
$out[(string) $k] = $v;
}
}
return $out;
}
}

View File

@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Api\Admin;
use CodeIgniter\HTTP\ResponseInterface;
class PresensiController extends BaseAdminApiController
{
public function index(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('presensi');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$this->auditAuthorized('api.admin.presensi.index', $auth['actor'], [
'request' => $this->auditRequestParams(),
]);
$today = date('Y-m-d');
$dari = (string) ($this->request->getGet('tanggal_dari') ?? $today);
$sampai = (string) ($this->request->getGet('tanggal_sampai') ?? $today);
if (strtotime($dari) === false || strtotime($sampai) === false) {
return $this->respond(['status' => 0, 'pesan' => 'Format tanggal tidak valid'], 400);
}
if ($dari > $sampai) {
[$dari, $sampai] = [$sampai, $dari];
}
$page = (int) ($this->request->getGet('page') ?? 1);
$perPage = (int) ($this->request->getGet('per_page') ?? 30);
$q = (string) ($this->request->getGet('q') ?? '');
return $this->respond($this->adminApi->presensiList($dari, $sampai, $page, $perPage, $q, $cb['kid']));
}
public function show(?string $id = null): ResponseInterface
{
$auth = $this->requireAdminApiAccess('presensi');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$this->auditAuthorized('api.admin.presensi.show', $auth['actor'], [
'request' => $this->auditRequestParams(),
'id' => $id,
]);
$idInt = (int) ($id ?? 0);
if ($idInt <= 0) {
return $this->respond(['status' => 0, 'pesan' => 'ID tidak valid'], 400);
}
return $this->respond($this->adminApi->presensiShow($idInt, $cb['kid']));
}
}

View File

@@ -0,0 +1,209 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Api\Admin;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Presensi: tugas luar, lembur, libur, jadwal, aktivitas harian.
*/
class PresensiToolsApiController extends BaseAdminApiController
{
public function dilapangan(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('presensi');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$this->auditAuthorized('api.admin.presensi.dilapangan.list', $auth['actor'], ['request' => $this->auditRequestParams()]);
return $this->respond($this->adminExtra->dilapanganList($cb['kid']));
}
public function dilapanganSave(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('presensi');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$post = $this->request->getPost();
$id = (int) ($post['id_dilapangan'] ?? 0);
$this->auditAuthorized('api.admin.presensi.dilapangan.save', $auth['actor'], ['id' => $id ?: null]);
return $this->respond($this->adminExtra->dilapanganSave($post, $id > 0 ? $id : null, $cb['kid']));
}
public function dilapanganDelete(int $id): ResponseInterface
{
$auth = $this->requireAdminApiAccess('presensi');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$this->auditAuthorized('api.admin.presensi.dilapangan.delete', $auth['actor'], ['id' => $id]);
return $this->respond($this->adminExtra->dilapanganDelete($id, $cb['kid']));
}
public function lembur(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('presensi');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$this->auditAuthorized('api.admin.presensi.lembur.list', $auth['actor'], ['request' => $this->auditRequestParams()]);
return $this->respond($this->adminExtra->lemburList($cb['kid']));
}
public function lemburSave(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('presensi');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$post = $this->request->getPost();
$id = (int) ($post['id_lembur'] ?? 0);
$this->auditAuthorized('api.admin.presensi.lembur.save', $auth['actor'], ['id' => $id ?: null]);
return $this->respond($this->adminExtra->lemburSave($post, $id > 0 ? $id : null, $cb['kid']));
}
public function lemburDelete(int $id): ResponseInterface
{
$auth = $this->requireAdminApiAccess('presensi');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$this->auditAuthorized('api.admin.presensi.lembur.delete', $auth['actor'], ['id' => $id]);
return $this->respond($this->adminExtra->lemburDelete($id, $cb['kid']));
}
public function libur(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('presensi_libur');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.presensi.libur.list', $auth['actor'], ['request' => $this->auditRequestParams()]);
return $this->respond($this->adminExtra->liburList());
}
public function liburSave(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('presensi_libur');
if ($auth['response'] !== null) {
return $auth['response'];
}
$post = $this->request->getPost();
$id = (int) ($post['id_libur'] ?? 0);
$this->auditAuthorized('api.admin.presensi.libur.save', $auth['actor'], ['id' => $id ?: null]);
return $this->respond($this->adminExtra->liburSave($post, $id > 0 ? $id : null));
}
public function liburDelete(int $id): ResponseInterface
{
$auth = $this->requireAdminApiAccess('presensi_libur');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.presensi.libur.delete', $auth['actor'], ['id' => $id]);
return $this->respond($this->adminExtra->liburDelete($id));
}
public function jadwal(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('presensi_jadwal');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.presensi.jadwal.list', $auth['actor'], ['request' => $this->auditRequestParams()]);
return $this->respond($this->adminExtra->jadwalList());
}
public function jadwalSave(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('presensi_jadwal');
if ($auth['response'] !== null) {
return $auth['response'];
}
$post = $this->request->getPost();
$id = (int) ($post['id_jadwal'] ?? 0);
$this->auditAuthorized('api.admin.presensi.jadwal.save', $auth['actor'], ['id' => $id ?: null]);
return $this->respond($this->adminExtra->jadwalSave($post, $id > 0 ? $id : null));
}
public function jadwalDelete(int $id): ResponseInterface
{
$auth = $this->requireAdminApiAccess('presensi_jadwal');
if ($auth['response'] !== null) {
return $auth['response'];
}
$this->auditAuthorized('api.admin.presensi.jadwal.delete', $auth['actor'], ['id' => $id]);
return $this->respond($this->adminExtra->jadwalDelete($id));
}
public function aktivitas(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('presensi');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$page = max(1, (int) ($this->request->getGet('page') ?? 1));
$perPage = max(5, min(100, (int) ($this->request->getGet('per_page') ?? 20)));
$this->auditAuthorized('api.admin.presensi.aktivitas.list', $auth['actor'], ['request' => $this->auditRequestParams()]);
return $this->respond($this->adminExtra->aktifitasList($page, $perPage, $cb['kid']));
}
public function aktivitasDelete(int $id): ResponseInterface
{
$auth = $this->requireAdminApiAccess('presensi');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$this->auditAuthorized('api.admin.presensi.aktivitas.delete', $auth['actor'], ['id' => $id]);
return $this->respond($this->adminExtra->aktifitasDelete($id, $cb['kid']));
}
}

View File

@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Api\Admin;
use CodeIgniter\HTTP\ResponseInterface;
class ReferenceController extends BaseAdminApiController
{
public function index(): ResponseInterface
{
$auth = $this->requireAdminApiAccess('references');
if ($auth['response'] !== null) {
return $auth['response'];
}
$cb = $this->cabangKantorAfterAuth($auth['actor']);
if ($cb['response'] !== null) {
return $cb['response'];
}
$this->auditAuthorized('api.admin.references.index', $auth['actor'], [
'request' => $this->auditRequestParams(),
]);
return $this->respond($this->adminApi->references($cb['kid']));
}
}

View File

@@ -0,0 +1,214 @@
<?php
namespace App\Controllers\Api;
use App\Controllers\BaseController;
use App\Libraries\ApiParityLogger;
use App\Libraries\LegacyUtf8Encoder;
use App\Services\Mobile\MobileJsonService;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Pengganti CI3 `application/controllers/Json.php`.
*
* URL CI4: POST /api/mobile/{method}
* URL CI3: POST /index.php/json/{method}
*
* @see docs/migration/json_api_map.md
*/
class MobileJsonController extends BaseController
{
protected MobileJsonService $mobileJson;
public function initController(\CodeIgniter\HTTP\RequestInterface $request, ResponseInterface $response, \Psr\Log\LoggerInterface $logger): void
{
parent::initController($request, $response, $logger);
$this->mobileJson = new MobileJsonService();
$this->response->setHeader('Access-Control-Allow-Origin', '*');
if (ApiParityLogger::enabled()) {
ApiParityLogger::logRequest($this->request);
}
}
/**
* @param array<string, mixed> $payload
*/
private function respondLegacy(array $payload): ResponseInterface
{
$body = LegacyUtf8Encoder::utf8ize($payload);
// CI3 memakai json_encode() default (tanpa JSON_UNESCAPED_UNICODE / PRETTY_PRINT).
$json = json_encode($body, 0, 512);
if ($json === false) {
$json = '{"status":0,"pesan":"JSON_ENCODE_ERROR"}';
}
if (ApiParityLogger::enabled()) {
ApiParityLogger::logResponse($json);
}
return $this->response->setStatusCode(200)
->setContentType('application/json', 'UTF-8')
->setBody($json);
}
public function login_w_token(): ResponseInterface
{
$token = (string) $this->request->getPost('token');
return $this->respondLegacy($this->mobileJson->loginWToken($token));
}
public function login(): ResponseInterface
{
$user = (string) $this->request->getPost('username');
$pass = (string) $this->request->getPost('password');
return $this->respondLegacy($this->mobileJson->login($user, $pass));
}
public function profil(): ResponseInterface
{
$token = (string) $this->request->getPost('token');
return $this->respondLegacy($this->mobileJson->profil($token));
}
public function save_cuti(): ResponseInterface
{
return $this->respondLegacy($this->mobileJson->saveCuti(
(string) $this->request->getPost('token'),
(string) $this->request->getPost('nama_photo'),
(string) $this->request->getPost('photo'),
(string) $this->request->getPost('tanggal'),
(string) $this->request->getPost('alasan'),
(string) $this->request->getPost('tipe'),
));
}
public function batalkan_cuti(): ResponseInterface
{
return $this->respondLegacy($this->mobileJson->batalkanCuti(
(string) $this->request->getPost('token'),
$this->request->getPost('id'),
));
}
public function save_aktifitas(): ResponseInterface
{
return $this->respondLegacy($this->mobileJson->saveAktifitas(
(string) $this->request->getPost('token'),
(string) $this->request->getPost('nama_photo'),
(string) $this->request->getPost('photo'),
(string) $this->request->getPost('tanggal'),
(string) $this->request->getPost('deksripsi'),
));
}
public function save_masuk(): ResponseInterface
{
return $this->respondLegacy($this->mobileJson->saveMasuk(
(string) $this->request->getPost('token'),
(string) $this->request->getPost('nama_photo'),
(string) $this->request->getPost('photo'),
(string) $this->request->getPost('lat'),
(string) $this->request->getPost('lng'),
(string) $this->request->getPost('jarak'),
));
}
public function save_pulang(): ResponseInterface
{
return $this->respondLegacy($this->mobileJson->savePulang(
(string) $this->request->getPost('token'),
(string) $this->request->getPost('nama_photo'),
(string) $this->request->getPost('photo'),
(string) $this->request->getPost('lat'),
(string) $this->request->getPost('lng'),
(string) $this->request->getPost('jarak'),
));
}
public function save_istirahat(): ResponseInterface
{
return $this->respondLegacy($this->mobileJson->saveIstirahat(
(string) $this->request->getPost('token'),
(string) $this->request->getPost('mulai'),
(string) $this->request->getPost('selesai'),
));
}
public function presensi_today(): ResponseInterface
{
return $this->respondLegacy($this->mobileJson->presensiToday((string) $this->request->getPost('token')));
}
public function presensi(): ResponseInterface
{
return $this->respondLegacy($this->mobileJson->presensi((string) $this->request->getPost('token')));
}
public function daftar_today(): ResponseInterface
{
return $this->respondLegacy($this->mobileJson->daftarToday((string) $this->request->getPost('token')));
}
public function berita(): ResponseInterface
{
return $this->respondLegacy($this->mobileJson->berita(
(string) $this->request->getPost('token'),
$this->request->getPost('dari'),
$this->request->getPost('jumlah'),
));
}
public function cuti(): ResponseInterface
{
return $this->respondLegacy($this->mobileJson->cuti(
(string) $this->request->getPost('token'),
$this->request->getPost('dari'),
$this->request->getPost('jumlah'),
));
}
public function lembur(): ResponseInterface
{
return $this->respondLegacy($this->mobileJson->lembur(
(string) $this->request->getPost('token'),
$this->request->getPost('dari'),
$this->request->getPost('jumlah'),
));
}
public function libur(): ResponseInterface
{
return $this->respondLegacy($this->mobileJson->libur((string) $this->request->getPost('token')));
}
public function aktifitas(): ResponseInterface
{
return $this->respondLegacy($this->mobileJson->aktifitas(
(string) $this->request->getPost('token'),
$this->request->getPost('dari'),
$this->request->getPost('jumlah'),
));
}
public function save_pp(): ResponseInterface
{
return $this->respondLegacy($this->mobileJson->savePp(
(string) $this->request->getPost('token'),
(string) $this->request->getPost('nama_photo'),
(string) $this->request->getPost('photo'),
));
}
public function save_password(): ResponseInterface
{
return $this->respondLegacy($this->mobileJson->savePassword(
(string) $this->request->getPost('token'),
(string) $this->request->getPost('pass_lama'),
(string) $this->request->getPost('pass_baru'),
));
}
}

View File

@@ -0,0 +1,45 @@
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
/**
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
*
* Extend this class in any new controllers:
* ```
* class Home extends BaseController
* ```
*
* For security, be sure to declare any new methods as protected or private.
*/
abstract class BaseController extends Controller
{
/**
* Be sure to declare properties for any property fetch you initialized.
* The creation of dynamic property is deprecated in PHP 8.2.
*/
// protected $session;
/**
* @return void
*/
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Load here all helpers you want to be available in your controllers that extend BaseController.
// Caution: Do not put the this below the parent::initController() call below.
$this->helpers = array_merge($this->helpers ?? [], ['url']);
// Caution: Do not edit this line.
parent::initController($request, $response, $logger);
// Preload any models, libraries, etc, here.
// $this->session = service('session');
}
}

11
app/Controllers/Home.php Normal file
View File

@@ -0,0 +1,11 @@
<?php
namespace App\Controllers;
class Home extends BaseController
{
public function index(): string
{
return view('welcome_message');
}
}

View File

View File

@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateAdminActivityLogs extends Migration
{
public function up(): void
{
$this->forge->addField([
'id' => [
'type' => 'BIGINT',
'unsigned' => true,
'auto_increment' => true,
],
'admin_user' => [
'type' => 'VARCHAR',
'constraint' => 191,
'default' => '',
],
'action' => [
'type' => 'VARCHAR',
'constraint' => 128,
'default' => '',
],
'endpoint' => [
'type' => 'VARCHAR',
'constraint' => 512,
'default' => '',
],
'payload' => [
'type' => 'TEXT',
'null' => true,
],
'ip_address' => [
'type' => 'VARCHAR',
'constraint' => 45,
'default' => '',
],
'user_agent' => [
'type' => 'VARCHAR',
'constraint' => 512,
'default' => '',
],
'auth_source' => [
'type' => 'VARCHAR',
'constraint' => 32,
'null' => true,
],
'roles_json' => [
'type' => 'TEXT',
'null' => true,
],
'outcome' => [
'type' => 'VARCHAR',
'constraint' => 32,
'default' => 'success',
],
'created_at' => [
'type' => 'DATETIME',
'null' => false,
],
]);
$this->forge->addKey('id', true);
$this->forge->addKey('created_at');
$this->forge->addKey(['action', 'created_at']);
$this->forge->createTable('admin_activity_logs', true, [
'ENGINE' => 'InnoDB',
]);
}
public function down(): void
{
$this->forge->dropTable('admin_activity_logs', true);
}
}

View File

@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddIdPegawaiToAdminUsers extends Migration
{
public function up(): void
{
if (! $this->db->tableExists('admin_users')) {
return;
}
if ($this->db->fieldExists('id_pegawai', 'admin_users')) {
return;
}
$this->forge->addColumn('admin_users', [
'id_pegawai' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
],
]);
}
public function down(): void
{
if (! $this->db->tableExists('admin_users')) {
return;
}
if (! $this->db->fieldExists('id_pegawai', 'admin_users')) {
return;
}
$this->forge->dropColumn('admin_users', 'id_pegawai');
}
}

View File

0
app/Filters/.gitkeep Normal file
View File

32
app/Filters/AuthAdmin.php Normal file
View File

@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
class AuthAdmin implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null): ?ResponseInterface
{
$token = session()->get('admin_mobile_token');
if (is_string($token) && $token !== '') {
return null;
}
if ($request->isAJAX()) {
return service('response')
->setStatusCode(401)
->setJSON(['status' => 0, 'pesan' => 'Unauthorized']);
}
return redirect()->to(site_url('admin/login'))->with('error', 'Silakan login terlebih dahulu.');
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null): void
{
}
}

0
app/Helpers/.gitkeep Normal file
View File

View File

@@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
if (! function_exists('cuti_tanggal_label')) {
/**
* Label tanggal cuti untuk tampilan admin (d/m/Y). Nilai tidak valid → tanda em dash.
* Menerima string (Y-m-d, ISO datetime, d/m/Y), DateTimeInterface, angka 8 digit yyyymmdd, atau array hasil JSON aneh.
*/
function cuti_tanggal_label(mixed $raw): string
{
if ($raw === null || $raw === '') {
return '—';
}
if (is_array($raw)) {
$raw = $raw['date'] ?? $raw['value'] ?? null;
if ($raw === null || $raw === '') {
return '—';
}
}
if ($raw instanceof \DateTimeInterface) {
return $raw->format('d/m/Y');
}
if (is_object($raw) && ! $raw instanceof \Stringable) {
return '—';
}
if ($raw instanceof \Stringable) {
$raw = (string) $raw;
}
if (is_int($raw)) {
$s = (string) $raw;
if (strlen($s) === 8 && preg_match('/^\d{8}$/', $s)) {
$y = substr($s, 0, 4);
$m = substr($s, 4, 2);
$d = substr($s, 6, 2);
$ts = strtotime($y . '-' . $m . '-' . $d);
return $ts !== false ? date('d/m/Y', $ts) : '—';
}
return '—';
}
if (is_float($raw)) {
return '—';
}
if (! is_string($raw)) {
return '—';
}
$s = trim($raw);
if ($s === '' || str_starts_with($s, '0000-00-00')) {
return '—';
}
if (preg_match('/^(\d{4}-\d{1,2}-\d{1,2})/', $s, $m)) {
$ts = strtotime($m[1]);
if ($ts !== false) {
return date('d/m/Y', $ts);
}
}
foreach (['!d/m/Y', '!d-m-Y', '!j/n/Y', '!j-n-Y'] as $fmt) {
$dt = \DateTimeImmutable::createFromFormat($fmt, $s);
if ($dt instanceof \DateTimeImmutable) {
return $dt->format('d/m/Y');
}
}
$ts = strtotime($s);
return $ts !== false ? date('d/m/Y', $ts) : '—';
}
}
if (! function_exists('cuti_tanggal_label_from_row')) {
/**
* Ambil tanggal cuti dari baris API/DB (kunci case-insensitive + fallback kolom umum).
*/
function cuti_tanggal_label_from_row(array $row): string
{
$lower = array_change_key_case($row, CASE_LOWER);
$raw = $lower['tanggal_cuti'] ?? $lower['tanggal'] ?? $lower['tgl_cuti'] ?? null;
return cuti_tanggal_label($raw);
}
}

104
app/Helpers/rbac_helper.php Normal file
View File

@@ -0,0 +1,104 @@
<?php
declare(strict_types=1);
use Config\AdminAccess;
if (! function_exists('admin_ion_roles')) {
/**
* Nama grup Ion dari sesi (sudah dinormalisasi string).
*
* @return list<string>
*/
function admin_ion_roles(): array
{
$raw = session()->get('admin_ion_groups');
if (! is_array($raw)) {
return [];
}
$out = [];
foreach ($raw as $g) {
$s = strtolower(trim((string) $g));
if ($s !== '') {
$out[] = $s;
}
}
return array_values(array_unique($out));
}
}
if (! function_exists('rbac_enforce_ion')) {
/**
* Grup Ion hanya relevan bila login dari tabel admin_users (Ion Auth).
* Login `pegawai` saja (tanpa admin terhubung) memakai {@see AdminAccess::$pegawaiPanelFeatures}.
*/
function rbac_enforce_ion(): bool
{
return session()->get('admin_auth_source') === 'admin_users';
}
}
if (! function_exists('hasRole')) {
function hasRole(string $role): bool
{
$want = strtolower(trim($role));
if ($want === '') {
return false;
}
foreach (admin_ion_roles() as $g) {
if ($g === $want) {
return true;
}
}
return false;
}
}
if (! function_exists('hasAnyRole')) {
/**
* @param list<string>|array<int, string> $roles
*/
function hasAnyRole(array $roles): bool
{
foreach ($roles as $r) {
if (hasRole((string) $r)) {
return true;
}
}
return false;
}
}
if (! function_exists('canAccess')) {
/**
* Cek akses fitur berdasarkan `Config\AdminAccess::$features`.
*/
function canAccess(string $feature): bool
{
/** @var AdminAccess $cfg */
$cfg = config('AdminAccess');
if (! isset($cfg->features[$feature])) {
return false;
}
if (! rbac_enforce_ion()) {
return in_array($feature, $cfg->pegawaiPanelFeatures, true);
}
$required = $cfg->features[$feature];
if ($required === []) {
return true;
}
if (admin_ion_roles() === []) {
return false;
}
return hasAnyRole($required);
}
}

0
app/Language/.gitkeep Normal file
View File

View File

@@ -0,0 +1,4 @@
<?php
// override core en language system validation or define your own en language validation message
return [];

0
app/Libraries/.gitkeep Normal file
View File

View File

@@ -0,0 +1,79 @@
<?php
namespace App\Libraries;
use CodeIgniter\HTTP\IncomingRequest;
/**
* Logging sementara untuk verifikasi parity CI3 ↔ CI4.
* Aktifkan dengan API_PARITY_LOG=true di .env (jangan di produksi jangka panjang).
*
* Output: writable/logs/api_parity-YYYY-MM-DD.log
*/
class ApiParityLogger
{
public static function enabled(): bool
{
return filter_var(env('API_PARITY_LOG', false), FILTER_VALIDATE_BOOLEAN);
}
public static function logRequest(IncomingRequest $request): void
{
if (! self::enabled()) {
return;
}
$post = $request->getPost() ?? [];
$post = self::sanitizePostForLog($post);
$line = sprintf(
"[%s] IN %s %s POST=%s\n",
date('Y-m-d H:i:s'),
$request->getMethod(),
$request->getUri()->getPath(),
json_encode($post, JSON_UNESCAPED_UNICODE)
);
self::append($line);
}
/**
* @param mixed $payloadBody utf8ize'd structure (array/object) before json_encode
*/
public static function logResponse(string $jsonBody): void
{
if (! self::enabled()) {
return;
}
$preview = strlen($jsonBody) > 8000 ? substr($jsonBody, 0, 8000) . '...[truncated]' : $jsonBody;
$line = sprintf("[%s] OUT %s\n", date('Y-m-d H:i:s'), $preview);
self::append($line);
}
private static function append(string $line): void
{
$path = WRITEPATH . 'logs' . DIRECTORY_SEPARATOR . 'api_parity-' . date('Y-m-d') . '.log';
@file_put_contents($path, $line, FILE_APPEND | LOCK_EX);
}
/**
* @param array<string, mixed> $post
*
* @return array<string, mixed>
*/
private static function sanitizePostForLog(array $post): array
{
foreach (['password', 'pass_lama', 'pass_baru'] as $k) {
if (array_key_exists($k, $post) && $post[$k] !== null && $post[$k] !== '') {
$post[$k] = '***';
}
}
if (isset($post['photo']) && is_string($post['photo']) && $post['photo'] !== '') {
$post['photo'] = '[base64 len=' . strlen($post['photo']) . ']';
}
return $post;
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace App\Libraries;
/**
* Replikasi perilaku utf8ize() dari CI3 Json controller (string ISO-8859-1 → UTF-8).
* Catatan: password/token tetap legacy (MD5 / token kolom) — lihat docs/migration/risks.md.
*/
class LegacyUtf8Encoder
{
/**
* @param mixed $d
*
* @return mixed
*/
public static function utf8ize($d)
{
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = self::utf8ize($v);
}
} elseif (is_string($d)) {
// Samakan dengan CI3 json.php utf8_encode() (Latin-1 → UTF-8).
if (function_exists('utf8_encode')) {
return @utf8_encode($d);
}
return mb_convert_encoding($d, 'UTF-8', 'ISO-8859-1');
}
return $d;
}
}

0
app/Models/.gitkeep Normal file
View File

View File

@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace App\Models;
use CodeIgniter\Model;
/**
* Pengguna panel admin CI3 (Ion Auth) — tabel admin_users.
*/
class AdminUserModel extends Model
{
protected $table = 'admin_users';
protected $primaryKey = 'id';
protected $returnType = 'array';
protected $allowedFields = [
'ip_address',
'username',
'password',
'salt',
'email',
'activation_code',
'forgotten_password_code',
'forgotten_password_time',
'remember_code',
'created_on',
'last_login',
'active',
'first_name',
'last_name',
'photo',
'nama_lengkap',
'no_telepon',
'id_pegawai',
];
}

View File

@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Models;
use CodeIgniter\Model;
class PegawaiModel extends Model
{
protected $table = 'pegawai';
protected $primaryKey = 'id_pegawai';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $protectFields = true;
/** @var list<string> */
protected $allowedFields = [
'nip',
'nama_lengkap',
'jenis_kelamin',
'tempat_lahir',
'tanggal_lahir',
'photo',
'email',
'jabatan',
'unit_kerja',
'golongan_pekerjaan',
'kantor',
'status_kepegawaian',
'tanggal_bergabung',
'jadwal',
'super_akses',
'username',
'password',
'token',
'last_login',
];
}

View File

@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace App\Models;
use CodeIgniter\Model;
class PresensiModel extends Model
{
protected $table = 'presensi';
protected $primaryKey = 'id_presensi';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $protectFields = true;
/** @var list<string> */
protected $allowedFields = [
'pegawai',
'tanggal',
'jadwal',
'jam_masuk',
'ket_masuk',
'photo_masuk',
'jam_pulang',
'ket_pulang',
'photo_pulang',
'mulai_istirahat',
'beres_istirahat',
'is_istirahat',
'lat_masuk',
'lng_masuk',
'lat_pulang',
'lng_pulang',
'jarak_masuk',
'jarak_pulang',
];
}

View File

@@ -0,0 +1,977 @@
<?php
declare(strict_types=1);
namespace App\Services\Admin;
use App\Models\PegawaiModel;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Database\BaseConnection;
use Config\Database;
use Config\Services;
/**
* Logika API admin (/api/admin/*) — akses DB hanya dari sini, bukan dari controller web admin.
*/
class AdminApiService
{
protected BaseConnection $db;
public function __construct(?BaseConnection $db = null)
{
$this->db = $db ?? Database::connect();
}
/**
* @return array<string, mixed>|null baris pegawai (tanpa password) atau null
*/
public function actorFromToken(string $token): ?array
{
if ($token === '') {
return null;
}
$row = $this->db->table('pegawai')->where('token', $token)->get()->getRowArray();
if ($row === null) {
return null;
}
unset($row['password']);
return $row;
}
/**
* @return array{status: int, pesan: string, data?: mixed}
*/
public function references(?int $cabangKantorId = null): array
{
$kantor = $this->db->table('kantor')->orderBy('nama_kantor')->get()->getResultArray();
if ($cabangKantorId !== null && $cabangKantorId > 0) {
$kantor = array_values(array_filter(
$kantor,
static fn ($r) => (int) ($r['id_kantor'] ?? 0) === $cabangKantorId
));
}
return [
'status' => 1,
'pesan' => 'OK',
'data' => [
'jabatan' => $this->db->table('jabatan')->orderBy('nama_jabatan')->get()->getResultArray(),
'unit_kerja' => $this->db->table('unit_kerja')->orderBy('nama_unit_kerja')->get()->getResultArray(),
'golongan' => $this->db->table('golongan')->orderBy('nama_golongan')->get()->getResultArray(),
'kantor' => $kantor,
'jadwal' => $this->db->table('jadwal')->orderBy('nama_jadwal')->get()->getResultArray(),
],
];
}
/**
* @return array{status: int, pesan: string, data?: mixed}
*/
public function pegawaiList(int $page, int $perPage, string $search = '', ?int $cabangKantorId = null): array
{
$perPage = max(5, min(500, $perPage));
$page = max(1, $page);
$offset = ($page - 1) * $perPage;
$countB = $this->db->table('pegawai p')
->join('jabatan j', 'j.id_jabatan = p.jabatan', 'left')
->join('unit_kerja u', 'u.id_unit_kerja = p.unit_kerja', 'left')
->join('golongan g', 'g.id_golongan = p.golongan_pekerjaan', 'left')
->join('kantor k', 'k.id_kantor = p.kantor', 'left')
->join('jadwal jd', 'jd.id_jadwal = p.jadwal', 'left');
$this->applyCabangPegawaiAlias($countB, 'p', $cabangKantorId);
$this->applyPegawaiSearchFilter($countB, $search);
$total = (int) $countB->countAllResults();
$b = $this->db->table('pegawai p')
->select('p.id_pegawai, p.nip, p.nama_lengkap, p.jenis_kelamin, p.photo, p.email, p.jabatan, p.unit_kerja, p.golongan_pekerjaan, p.kantor, p.jadwal, p.status_kepegawaian, p.super_akses')
->select('j.nama_jabatan, u.nama_unit_kerja, g.nama_golongan, k.nama_kantor, jd.nama_jadwal')
->join('jabatan j', 'j.id_jabatan = p.jabatan', 'left')
->join('unit_kerja u', 'u.id_unit_kerja = p.unit_kerja', 'left')
->join('golongan g', 'g.id_golongan = p.golongan_pekerjaan', 'left')
->join('kantor k', 'k.id_kantor = p.kantor', 'left')
->join('jadwal jd', 'jd.id_jadwal = p.jadwal', 'left');
$this->applyCabangPegawaiAlias($b, 'p', $cabangKantorId);
$this->applyPegawaiSearchFilter($b, $search);
$rows = $b->orderBy('p.nama_lengkap', 'ASC')
->limit($perPage, $offset)
->get()
->getResultArray();
return [
'status' => 1,
'pesan' => 'OK',
'data' => [
'rows' => $rows,
'total' => $total,
'page' => $page,
'per_page' => $perPage,
'total_page' => (int) ceil($total / $perPage),
],
];
}
/**
* @return array{status: int, pesan: string, data?: mixed}
*/
public function pegawaiShow(int $id, ?int $cabangKantorId = null): array
{
$row = $this->fetchPegawaiDetail($id);
if ($row === null) {
return ['status' => 0, 'pesan' => 'Data pegawai tidak ditemukan'];
}
if (! $this->pegawaiRowInCabang($row, $cabangKantorId)) {
return ['status' => 0, 'pesan' => 'Data pegawai tidak ditemukan'];
}
return ['status' => 1, 'pesan' => 'OK', 'data' => $row];
}
/**
* @param array<string, scalar|null> $input
*
* @return array{status: int, pesan: string, data?: mixed}
*/
public function pegawaiCreate(array $input, ?int $cabangKantorId = null): array
{
$validation = Services::validation();
$validation->setRules([
'nip' => 'required|max_length[50]|is_unique[pegawai.nip]',
'nama_lengkap' => 'required|max_length[50]',
'jenis_kelamin' => 'required|in_list[Pria,Wanita]',
'tempat_lahir' => 'permit_empty|max_length[100]',
'tanggal_lahir' => 'permit_empty|valid_date',
'email' => 'permit_empty|max_length[50]',
'jabatan' => 'required|integer',
'unit_kerja' => 'required|integer',
'golongan_pekerjaan' => 'required|integer',
'kantor' => 'required|integer',
'status_kepegawaian' => 'required|in_list[Kontrak,Pegawai Tetap]',
'tanggal_bergabung' => 'required|valid_date',
'jadwal' => 'required|integer',
'super_akses' => 'permit_empty|in_list[false,true]',
'photo' => 'permit_empty|max_length[255]',
'username' => 'required|max_length[50]|is_unique[pegawai.username]',
'password' => 'permit_empty|max_length[50]',
]);
if (! $validation->run($input)) {
return ['status' => 0, 'pesan' => implode(' ', $validation->getErrors())];
}
if ($cabangKantorId !== null && $cabangKantorId > 0 && (int) $input['kantor'] !== $cabangKantorId) {
return ['status' => 0, 'pesan' => 'Cabang pegawai harus sama dengan cabang Anda.'];
}
$nip = (string) $input['nip'];
$password = isset($input['password']) && (string) $input['password'] !== ''
? md5((string) $input['password'])
: md5($nip);
$model = new PegawaiModel();
$kantorVal = $cabangKantorId !== null && $cabangKantorId > 0 ? $cabangKantorId : (int) $input['kantor'];
$photoIn = trim((string) ($input['photo'] ?? ''));
$data = [
'nip' => $nip,
'nama_lengkap' => (string) $input['nama_lengkap'],
'jenis_kelamin' => (string) $input['jenis_kelamin'],
'tempat_lahir' => (string) ($input['tempat_lahir'] ?? ''),
'tanggal_lahir' => $this->normalizeDate($input['tanggal_lahir'] ?? null),
'photo' => $photoIn === '' || $photoIn === '-' ? '' : substr($photoIn, 0, 255),
'email' => (string) ($input['email'] ?? ''),
'jabatan' => (int) $input['jabatan'],
'unit_kerja' => (int) $input['unit_kerja'],
'golongan_pekerjaan' => (int) $input['golongan_pekerjaan'],
'kantor' => $kantorVal,
'status_kepegawaian' => (string) $input['status_kepegawaian'],
'tanggal_bergabung' => (string) $input['tanggal_bergabung'],
'jadwal' => (int) $input['jadwal'],
'super_akses' => (string) ($input['super_akses'] ?? 'false'),
'username' => (string) $input['username'],
'password' => $password,
'token' => '',
'last_login' => null,
];
if ($model->insert($data, true) === false) {
return ['status' => 0, 'pesan' => implode(' ', $model->errors())];
}
$id = (int) $model->getInsertID();
return ['status' => 1, 'pesan' => 'Data berhasil disimpan', 'data' => ['id_pegawai' => $id]];
}
/**
* @param array<string, scalar|null> $input
*
* @return array{status: int, pesan: string, data?: mixed}
*/
public function pegawaiUpdate(int $id, array $input, ?int $cabangKantorId = null): array
{
$model = new PegawaiModel();
if ($model->find($id) === null) {
return ['status' => 0, 'pesan' => 'Data pegawai tidak ditemukan'];
}
if (! $this->pegawaiIdAllowedForCabang($id, $cabangKantorId)) {
return ['status' => 0, 'pesan' => 'Data pegawai tidak ditemukan'];
}
$validation = Services::validation();
$validation->setRules([
'nip' => "required|max_length[50]|is_unique[pegawai.nip,id_pegawai,{$id}]",
'nama_lengkap' => 'required|max_length[50]',
'jenis_kelamin' => 'required|in_list[Pria,Wanita]',
'tempat_lahir' => 'permit_empty|max_length[100]',
'tanggal_lahir' => 'permit_empty|valid_date',
'email' => 'permit_empty|max_length[50]',
'jabatan' => 'required|integer',
'unit_kerja' => 'required|integer',
'golongan_pekerjaan' => 'required|integer',
'kantor' => 'required|integer',
'status_kepegawaian' => 'required|in_list[Kontrak,Pegawai Tetap]',
'tanggal_bergabung' => 'required|valid_date',
'jadwal' => 'required|integer',
'super_akses' => 'permit_empty|in_list[false,true]',
'photo' => 'permit_empty|max_length[255]',
'username' => "required|max_length[50]|is_unique[pegawai.username,id_pegawai,{$id}]",
'password' => 'permit_empty|max_length[50]',
]);
if (! $validation->run($input)) {
return ['status' => 0, 'pesan' => implode(' ', $validation->getErrors())];
}
if ($cabangKantorId !== null && $cabangKantorId > 0 && (int) $input['kantor'] !== $cabangKantorId) {
return ['status' => 0, 'pesan' => 'Cabang pegawai harus sama dengan cabang Anda.'];
}
$kantorVal = $cabangKantorId !== null && $cabangKantorId > 0 ? $cabangKantorId : (int) $input['kantor'];
$data = [
'nip' => (string) $input['nip'],
'nama_lengkap' => (string) $input['nama_lengkap'],
'jenis_kelamin' => (string) $input['jenis_kelamin'],
'tempat_lahir' => (string) ($input['tempat_lahir'] ?? ''),
'tanggal_lahir' => $this->normalizeDate($input['tanggal_lahir'] ?? null),
'email' => (string) ($input['email'] ?? ''),
'jabatan' => (int) $input['jabatan'],
'unit_kerja' => (int) $input['unit_kerja'],
'golongan_pekerjaan' => (int) $input['golongan_pekerjaan'],
'kantor' => $kantorVal,
'status_kepegawaian' => (string) $input['status_kepegawaian'],
'tanggal_bergabung' => (string) $input['tanggal_bergabung'],
'jadwal' => (int) $input['jadwal'],
'super_akses' => (string) ($input['super_akses'] ?? 'false'),
'username' => (string) $input['username'],
];
if (array_key_exists('photo', $input)) {
$p = trim((string) $input['photo']);
$data['photo'] = $p === '' || $p === '-' ? '' : substr($p, 0, 255);
}
if (isset($input['password']) && (string) $input['password'] !== '') {
$data['password'] = md5((string) $input['password']);
}
if ($model->update($id, $data) === false) {
return ['status' => 0, 'pesan' => implode(' ', $model->errors())];
}
return ['status' => 1, 'pesan' => 'Data berhasil diperbarui'];
}
/**
* @return array{status: int, pesan: string}
*/
public function pegawaiDelete(int $id, ?int $cabangKantorId = null): array
{
$model = new PegawaiModel();
if ($model->find($id) === null) {
return ['status' => 0, 'pesan' => 'Data pegawai tidak ditemukan'];
}
if (! $this->pegawaiIdAllowedForCabang($id, $cabangKantorId)) {
return ['status' => 0, 'pesan' => 'Data pegawai tidak ditemukan'];
}
try {
$model->delete($id, true);
} catch (\Throwable $e) {
return ['status' => 0, 'pesan' => 'Tidak dapat menghapus pegawai (kemungkinan masih direferensikan data lain).'];
}
return ['status' => 1, 'pesan' => 'Data pegawai telah dihapus'];
}
/**
* Setel ulang password ke md5(NIP) dan kosongkan token (seperti CI3 admin).
*
* @return array{status: int, pesan: string}
*/
public function pegawaiResetPassword(int $id, ?int $cabangKantorId = null): array
{
$row = $this->db->table('pegawai')->select('id_pegawai, nip')->where('id_pegawai', $id)->get()->getRowArray();
if ($row === null) {
return ['status' => 0, 'pesan' => 'Data pegawai tidak ditemukan'];
}
if (! $this->pegawaiIdAllowedForCabang($id, $cabangKantorId)) {
return ['status' => 0, 'pesan' => 'Data pegawai tidak ditemukan'];
}
$this->db->table('pegawai')->where('id_pegawai', $id)->update([
'password' => md5((string) $row['nip']),
'token' => '',
]);
return ['status' => 1, 'pesan' => 'Password direset ke NIP (hash MD5) dan token dikosongkan.'];
}
/**
* Batasi query ke baris presensi yang sudah ada minimal satu rekam nyata.
* Baris "kosong" dari API mobile presensi_today (pegawai buka app → insert stub) tidak ikut.
*/
protected function applyPresensiHasMinimalRekam(BaseBuilder $builder): void
{
$builder->where(
'(
(pr.jam_masuk IS NOT NULL AND TRIM(CAST(pr.jam_masuk AS CHAR)) NOT IN (\'\',\'00:00\',\'00:00:00\'))
OR (pr.jam_pulang IS NOT NULL AND TRIM(CAST(pr.jam_pulang AS CHAR)) NOT IN (\'\',\'00:00\',\'00:00:00\'))
OR (pr.mulai_istirahat IS NOT NULL AND TRIM(CAST(pr.mulai_istirahat AS CHAR)) NOT IN (\'\',\'00:00\',\'00:00:00\'))
OR (pr.beres_istirahat IS NOT NULL AND TRIM(CAST(pr.beres_istirahat AS CHAR)) NOT IN (\'\',\'00:00\',\'00:00:00\'))
OR (pr.photo_masuk IS NOT NULL AND TRIM(CAST(pr.photo_masuk AS CHAR)) <> \'\')
OR (pr.photo_pulang IS NOT NULL AND TRIM(CAST(pr.photo_pulang AS CHAR)) <> \'\')
)',
null,
false
);
}
/**
* Daftar pegawai (sesuai cabang) yang hari ini belum presensi minimal dan bukan cuti Approve.
*
* @return list<array{id_pegawai: int, nama_lengkap: string, nip: string}>
*/
private function belumRekamPegawaiHariIni(string $tanggalHariIni, ?int $cabangKantorId): array
{
$hadPresensi = $this->db->table('presensi pr')
->select('pr.pegawai')
->distinct()
->join('pegawai pg', 'pg.id_pegawai = pr.pegawai', 'inner')
->where('pr.tanggal', $tanggalHariIni);
$this->applyPresensiHasMinimalRekam($hadPresensi);
$this->applyCabangPegawaiAlias($hadPresensi, 'pg', $cabangKantorId);
$idsP = [];
foreach ($hadPresensi->get()->getResultArray() as $r) {
$id = (int) ($r['pegawai'] ?? 0);
if ($id > 0) {
$idsP[] = $id;
}
}
$hadCuti = $this->db->table('cuti c')
->select('c.pegawai')
->distinct()
->join('pegawai p', 'p.id_pegawai = c.pegawai', 'inner')
->where('c.tanggal_cuti', $tanggalHariIni)
->where('c.status_cuti', 'Approve');
$this->applyCabangPegawaiAlias($hadCuti, 'p', $cabangKantorId);
$idsC = [];
foreach ($hadCuti->get()->getResultArray() as $r) {
$id = (int) ($r['pegawai'] ?? 0);
if ($id > 0) {
$idsC[] = $id;
}
}
$exclude = array_values(array_unique(array_merge($idsP, $idsC)));
$qb = $this->db->table('pegawai p')
->select('p.id_pegawai, p.nama_lengkap, p.nip')
->orderBy('p.nama_lengkap', 'ASC');
$this->applyCabangPegawaiAlias($qb, 'p', $cabangKantorId);
if ($exclude !== []) {
$qb->whereNotIn('p.id_pegawai', $exclude);
}
$out = [];
foreach ($qb->get()->getResultArray() as $row) {
if (! is_array($row)) {
continue;
}
$out[] = [
'id_pegawai' => (int) ($row['id_pegawai'] ?? 0),
'nama_lengkap' => (string) ($row['nama_lengkap'] ?? ''),
'nip' => (string) ($row['nip'] ?? ''),
];
}
return $out;
}
/**
* @return array{status: int, pesan: string, data?: mixed}
*/
public function presensiList(string $tanggalDari, string $tanggalSampai, int $page, int $perPage, string $search = '', ?int $cabangKantorId = null): array
{
$perPage = max(5, min(200, $perPage));
$page = max(1, $page);
$offset = ($page - 1) * $perPage;
$search = trim($search);
$countB = $this->db->table('presensi pr')
->join('pegawai pg', 'pg.id_pegawai = pr.pegawai', 'left')
->where('pr.tanggal >=', $tanggalDari)
->where('pr.tanggal <=', $tanggalSampai);
$this->applyPresensiHasMinimalRekam($countB);
$this->applyCabangPegawaiAlias($countB, 'pg', $cabangKantorId);
if ($search !== '') {
$countB->groupStart()
->like('pg.nama_lengkap', $search)
->orLike('pg.nip', $search)
->groupEnd();
}
$total = (int) $countB->countAllResults();
$b = $this->db->table('presensi pr')
->select('pr.*, pg.nama_lengkap, pg.nip')
->join('pegawai pg', 'pg.id_pegawai = pr.pegawai', 'left')
->where('pr.tanggal >=', $tanggalDari)
->where('pr.tanggal <=', $tanggalSampai);
$this->applyPresensiHasMinimalRekam($b);
$this->applyCabangPegawaiAlias($b, 'pg', $cabangKantorId);
if ($search !== '') {
$b->groupStart()
->like('pg.nama_lengkap', $search)
->orLike('pg.nip', $search)
->groupEnd();
}
$rows = $b->orderBy('pr.tanggal', 'DESC')
->orderBy('pg.nama_lengkap', 'ASC')
->limit($perPage, $offset)
->get()
->getResultArray();
return [
'status' => 1,
'pesan' => 'OK',
'data' => [
'rows' => $rows,
'total' => $total,
'page' => $page,
'per_page' => $perPage,
'total_page' => (int) ceil($total / $perPage),
'tanggal_dari' => $tanggalDari,
'tanggal_sampai' => $tanggalSampai,
'q' => $search,
],
];
}
/**
* @return array{status: int, pesan: string, data?: mixed}
*/
public function presensiShow(int $id, ?int $cabangKantorId = null): array
{
$row = $this->db->table('presensi pr')
->select('pr.*, pg.nama_lengkap, pg.nip, pg.email, pg.kantor as pegawai_kantor')
->join('pegawai pg', 'pg.id_pegawai = pr.pegawai', 'left')
->where('pr.id_presensi', $id)
->get()
->getRowArray();
if ($row === null) {
return ['status' => 0, 'pesan' => 'Data presensi tidak ditemukan'];
}
if (! $this->pegawaiRowInCabang(['kantor' => $row['pegawai_kantor'] ?? null], $cabangKantorId)) {
return ['status' => 0, 'pesan' => 'Data presensi tidak ditemukan'];
}
unset($row['pegawai_kantor']);
return ['status' => 1, 'pesan' => 'OK', 'data' => $row];
}
/**
* Ringkasan seperti dashboard admin CI3 (Home): pegawai, presensi & cuti per rentang tanggal.
*
* @return array{status: int, pesan: string, data?: mixed}
*/
public function laporanSummary(string $tanggalDari, string $tanggalSampai, ?int $cabangKantorId = null): array
{
$pegawaiBase = $this->db->table('pegawai');
$this->applyCabangPegawaiAlias($pegawaiBase, 'pegawai', $cabangKantorId);
$totalPegawai = (int) $pegawaiBase->countAllResults();
$presensiQb = $this->db->table('presensi pr')
->join('pegawai pg', 'pg.id_pegawai = pr.pegawai', 'inner')
->where('pr.tanggal >=', $tanggalDari)
->where('pr.tanggal <=', $tanggalSampai);
$this->applyPresensiHasMinimalRekam($presensiQb);
$this->applyCabangPegawaiAlias($presensiQb, 'pg', $cabangKantorId);
$presensiQ = (int) $presensiQb->countAllResults();
$cutiQb = $this->db->table('cuti c')
->join('pegawai p', 'p.id_pegawai = c.pegawai', 'inner')
->where('c.tanggal_cuti >=', $tanggalDari)
->where('c.tanggal_cuti <=', $tanggalSampai)
->where('c.status_cuti', 'Approve');
$this->applyCabangPegawaiAlias($cutiQb, 'p', $cabangKantorId);
$cutiQ = (int) $cutiQb->countAllResults();
$hariIni = date('Y-m-d');
$ph = $this->db->table('presensi pr')
->join('pegawai pg', 'pg.id_pegawai = pr.pegawai', 'inner')
->where('pr.tanggal', $hariIni);
$this->applyPresensiHasMinimalRekam($ph);
$this->applyCabangPegawaiAlias($ph, 'pg', $cabangKantorId);
$presensiHariIni = (int) $ph->countAllResults();
$ch = $this->db->table('cuti c')
->join('pegawai p', 'p.id_pegawai = c.pegawai', 'inner')
->where('c.tanggal_cuti', $hariIni)
->where('c.status_cuti', 'Approve');
$this->applyCabangPegawaiAlias($ch, 'p', $cabangKantorId);
$cutiHariIni = (int) $ch->countAllResults();
$belumRekam = max(0, $totalPegawai - $presensiHariIni - $cutiHariIni);
return [
'status' => 1,
'pesan' => 'OK',
'data' => [
'total_pegawai' => $totalPegawai,
'rentang' => ['dari' => $tanggalDari, 'sampai' => $tanggalSampai],
'presensi_rekam' => $presensiQ,
'cuti_approve' => $cutiQ,
'hari_ini' => $hariIni,
'presensi_hari_ini' => $presensiHariIni,
'cuti_hari_ini' => $cutiHariIni,
'belum_rekam_hari_ini' => $belumRekam,
],
];
}
/**
* Dashboard beranda admin — selaras `modules/admin/controllers/Home.php` CI3.
*
* @param int|null $soloPegawaiId Bila diisi (login panel sebagai pegawai saja), angka & cuti
* hanya untuk pegawai tersebut — bukan agregat seluruh perusahaan.
*
* @return array{status: int, pesan: string, data?: mixed}
*/
public function dashboardHome(?int $cabangKantorId = null, ?int $soloPegawaiId = null): array
{
$tanggalHariIni = date('Y-m-d');
if ($soloPegawaiId !== null && $soloPegawaiId > 0) {
return $this->dashboardHomeSoloPegawai($tanggalHariIni, $soloPegawaiId);
}
$pb = $this->db->table('pegawai');
$this->applyCabangPegawaiAlias($pb, 'pegawai', $cabangKantorId);
$totalPegawai = (int) $pb->countAllResults();
$pbL = $this->db->table('pegawai')->where('jenis_kelamin', 'Pria');
$this->applyCabangPegawaiAlias($pbL, 'pegawai', $cabangKantorId);
$pegawaiLaki = (int) $pbL->countAllResults();
$pbP = $this->db->table('pegawai')->where('jenis_kelamin', 'Wanita');
$this->applyCabangPegawaiAlias($pbP, 'pegawai', $cabangKantorId);
$pegawaiPerempuan = (int) $pbP->countAllResults();
$ph = $this->db->table('presensi pr')
->join('pegawai pg', 'pg.id_pegawai = pr.pegawai', 'inner')
->where('pr.tanggal', $tanggalHariIni);
$this->applyPresensiHasMinimalRekam($ph);
$this->applyCabangPegawaiAlias($ph, 'pg', $cabangKantorId);
$presensiHariIni = (int) $ph->countAllResults();
$ch = $this->db->table('cuti c')
->join('pegawai p', 'p.id_pegawai = c.pegawai', 'inner')
->where('c.tanggal_cuti', $tanggalHariIni)
->where('c.status_cuti', 'Approve');
$this->applyCabangPegawaiAlias($ch, 'p', $cabangKantorId);
$cutiHariIni = (int) $ch->countAllResults();
$belumRekam = max(0, $totalPegawai - $presensiHariIni - $cutiHariIni);
$belumRekamPegawai = $this->belumRekamPegawaiHariIni($tanggalHariIni, $cabangKantorId);
$persenLaki = $totalPegawai > 0 ? round(($pegawaiLaki / $totalPegawai) * 100, 1) : 0.0;
$persenPerempuan = $totalPegawai > 0 ? round(($pegawaiPerempuan / $totalPegawai) * 100, 1) : 0.0;
$persenPresensi = $totalPegawai > 0 ? round(($presensiHariIni / $totalPegawai) * 100, 1) : 0.0;
$persenCuti = $totalPegawai > 0 ? round(($cutiHariIni / $totalPegawai) * 100, 1) : 0.0;
$persenBelumRekam = $totalPegawai > 0 ? round(($belumRekam / $totalPegawai) * 100, 1) : 0.0;
$permohonanCutiB = $this->db->table('cuti c')
->select('c.id_cuti, c.pegawai, DATE_FORMAT(c.tanggal_cuti, \'%Y-%m-%d\') AS tanggal_cuti, c.tipe_cuti, c.alasan_cuti, c.status_cuti, p.nama_lengkap, p.nip', false)
->join('pegawai p', 'p.id_pegawai = c.pegawai', 'left')
->where('c.status_cuti', 'Waiting');
$this->applyCabangPegawaiAlias($permohonanCutiB, 'p', $cabangKantorId);
$permohonanCuti = $permohonanCutiB->orderBy('c.tanggal_cuti', 'ASC')
->limit(5)
->get()
->getResultArray();
$permohonanCuti = array_map(
fn ($r): array => is_array($r) ? $this->normalizeCutiRowArrayForApi($r) : [],
$permohonanCuti,
);
$tpc = $this->db->table('cuti c')
->join('pegawai p', 'p.id_pegawai = c.pegawai', 'inner')
->where('c.status_cuti', 'Waiting');
$this->applyCabangPegawaiAlias($tpc, 'p', $cabangKantorId);
$totalPermohonanCuti = (int) $tpc->countAllResults();
return [
'status' => 1,
'pesan' => 'OK',
'data' => [
'tanggal_hari_ini' => $tanggalHariIni,
'total_pegawai' => $totalPegawai,
'pegawai_laki' => $pegawaiLaki,
'pegawai_perempuan' => $pegawaiPerempuan,
'presensi_hari_ini' => $presensiHariIni,
'cuti_hari_ini' => $cutiHariIni,
'belum_rekam' => $belumRekam,
'persen_laki' => $persenLaki,
'persen_perempuan' => $persenPerempuan,
'persen_presensi' => $persenPresensi,
'persen_cuti' => $persenCuti,
'persen_belum_rekam' => $persenBelumRekam,
'permohonan_cuti' => $permohonanCuti,
'total_permohonan_cuti' => $totalPermohonanCuti,
'belum_rekam_pegawai' => $belumRekamPegawai,
],
];
}
/**
* Ringkasan beranda untuk satu pegawai (sesi login mobile / non-Ion).
*
* @return array{status: int, pesan: string, data?: mixed}
*/
private function dashboardHomeSoloPegawai(string $tanggalHariIni, int $pegawaiId): array
{
$row = $this->db->table('pegawai')->select('id_pegawai, jenis_kelamin')->where('id_pegawai', $pegawaiId)->get()->getRowArray();
if ($row === null) {
return ['status' => 0, 'pesan' => 'Data pegawai tidak ditemukan'];
}
$jk = (string) ($row['jenis_kelamin'] ?? '');
$laki = $jk === 'Pria' ? 1 : 0;
$wanit = $jk === 'Wanita' ? 1 : 0;
$ph = $this->db->table('presensi pr')
->where('pr.pegawai', $pegawaiId)
->where('pr.tanggal', $tanggalHariIni);
$this->applyPresensiHasMinimalRekam($ph);
$presensiHariIni = (int) $ph->countAllResults();
$ch = $this->db->table('cuti c')
->where('c.pegawai', $pegawaiId)
->where('c.tanggal_cuti', $tanggalHariIni)
->where('c.status_cuti', 'Approve');
$cutiHariIni = (int) $ch->countAllResults();
$belumRekam = max(0, 1 - $presensiHariIni - $cutiHariIni);
$permohonanCutiB = $this->db->table('cuti c')
->select('c.id_cuti, c.pegawai, DATE_FORMAT(c.tanggal_cuti, \'%Y-%m-%d\') AS tanggal_cuti, c.tipe_cuti, c.alasan_cuti, c.status_cuti, p.nama_lengkap, p.nip', false)
->join('pegawai p', 'p.id_pegawai = c.pegawai', 'left')
->where('c.pegawai', $pegawaiId)
->where('c.status_cuti', 'Waiting');
$permohonanCuti = $permohonanCutiB->orderBy('c.tanggal_cuti', 'ASC')
->limit(5)
->get()
->getResultArray();
$permohonanCuti = array_map(
fn ($r): array => is_array($r) ? $this->normalizeCutiRowArrayForApi($r) : [],
$permohonanCuti,
);
$tpc = $this->db->table('cuti c')
->where('c.pegawai', $pegawaiId)
->where('c.status_cuti', 'Waiting');
$totalPermohonanCuti = (int) $tpc->countAllResults();
$totalPegawai = 1;
$persenLaki = $laki === 1 ? 100.0 : 0.0;
$persenWanita = $wanit === 1 ? 100.0 : 0.0;
if ($laki === 0 && $wanit === 0) {
$persenLaki = 0.0;
$persenWanita = 0.0;
}
$persenPresensi = $presensiHariIni >= 1 ? 100.0 : 0.0;
$persenCuti = $cutiHariIni >= 1 ? 100.0 : 0.0;
$persenBelumRekam = $belumRekam >= 1 ? 100.0 : 0.0;
return [
'status' => 1,
'pesan' => 'OK',
'data' => [
'tanggal_hari_ini' => $tanggalHariIni,
'total_pegawai' => $totalPegawai,
'pegawai_laki' => $laki,
'pegawai_perempuan' => $wanit,
'presensi_hari_ini' => $presensiHariIni,
'cuti_hari_ini' => $cutiHariIni,
'belum_rekam' => $belumRekam,
'persen_laki' => $persenLaki,
'persen_perempuan' => $persenWanita,
'persen_presensi' => $persenPresensi,
'persen_cuti' => $persenCuti,
'persen_belum_rekam' => $persenBelumRekam,
'permohonan_cuti' => $permohonanCuti,
'total_permohonan_cuti' => $totalPermohonanCuti,
'belum_rekam_pegawai' => [],
],
];
}
/**
* @return array{status: int, pesan: string, data?: mixed}
*/
public function cutiList(string $status, int $page, int $perPage, ?int $cabangKantorId = null): array
{
$allowed = ['', 'Waiting', 'Approve', 'Rejected', 'Cancelled'];
if (! in_array($status, $allowed, true)) {
$status = 'Waiting';
}
$perPage = max(5, min(200, $perPage));
$page = max(1, $page);
$offset = ($page - 1) * $perPage;
$countB = $this->db->table('cuti c')->join('pegawai p', 'p.id_pegawai = c.pegawai', 'left');
$this->applyCabangPegawaiAlias($countB, 'p', $cabangKantorId);
if ($status !== '') {
$countB->where('c.status_cuti', $status);
}
$total = (int) $countB->countAllResults();
$b = $this->db->table('cuti c')
->select('c.id_cuti, c.pegawai, DATE_FORMAT(c.tanggal_cuti, \'%Y-%m-%d\') AS tanggal_cuti, c.tipe_cuti, c.alasan_cuti, c.status_cuti, c.alasan_tolak, p.nama_lengkap, p.nip', false)
->join('pegawai p', 'p.id_pegawai = c.pegawai', 'left');
$this->applyCabangPegawaiAlias($b, 'p', $cabangKantorId);
if ($status !== '') {
$b->where('c.status_cuti', $status);
}
$rows = $b->orderBy('c.tanggal_cuti', 'DESC')
->orderBy('c.id_cuti', 'DESC')
->limit($perPage, $offset)
->get()
->getResultArray();
$rows = array_map(
fn ($r): array => is_array($r) ? $this->normalizeCutiRowArrayForApi($r) : [],
$rows,
);
return [
'status' => 1,
'pesan' => 'OK',
'data' => [
'rows' => $rows,
'total' => $total,
'page' => $page,
'per_page' => $perPage,
'total_page' => (int) ceil($total / $perPage),
'status_filter'=> $status,
],
];
}
/**
* @return array{status: int, pesan: string, data?: mixed}
*/
public function cutiShow(int $id, ?int $cabangKantorId = null): array
{
$row = $this->db->table('cuti c')
->select('c.id_cuti, c.pegawai, DATE_FORMAT(c.tanggal_cuti, \'%Y-%m-%d\') AS tanggal_cuti, c.tipe_cuti, c.alasan_cuti, c.status_cuti, c.alasan_tolak, p.nama_lengkap, p.nip, p.email, p.kantor as pegawai_kantor', false)
->join('pegawai p', 'p.id_pegawai = c.pegawai', 'left')
->where('c.id_cuti', $id)
->get()
->getRowArray();
if ($row === null) {
return ['status' => 0, 'pesan' => 'Data cuti tidak ditemukan'];
}
$row = $this->normalizeCutiRowArrayForApi($row);
if (! $this->pegawaiRowInCabang(['kantor' => $row['pegawai_kantor'] ?? null], $cabangKantorId)) {
return ['status' => 0, 'pesan' => 'Data cuti tidak ditemukan'];
}
unset($row['pegawai_kantor']);
$dok = $this->db->table('cuti_dokumen')->select('dokumen')->where('cuti', $id)->get()->getResultArray();
return [
'status' => 1,
'pesan' => 'OK',
'data' => [
'cuti' => $row,
'dokumen' => $dok,
],
];
}
/**
* @return array{status: int, pesan: string}
*/
public function cutiApprove(int $id, ?int $cabangKantorId = null): array
{
$exists = $this->db->table('cuti')->select('id_cuti')->where('id_cuti', $id)->get()->getRowArray();
if ($exists === null) {
return ['status' => 0, 'pesan' => 'Data cuti tidak ditemukan'];
}
if (! $this->cutiAllowedForCabang($id, $cabangKantorId)) {
return ['status' => 0, 'pesan' => 'Data cuti tidak ditemukan'];
}
$this->db->table('cuti')->where('id_cuti', $id)->update([
'status_cuti' => 'Approve',
'alasan_tolak' => '',
]);
return ['status' => 1, 'pesan' => 'Cuti disetujui.'];
}
/**
* @return array{status: int, pesan: string}
*/
public function cutiReject(int $id, string $alasanTolak, ?int $cabangKantorId = null): array
{
$exists = $this->db->table('cuti')->select('id_cuti')->where('id_cuti', $id)->get()->getRowArray();
if ($exists === null) {
return ['status' => 0, 'pesan' => 'Data cuti tidak ditemukan'];
}
if (! $this->cutiAllowedForCabang($id, $cabangKantorId)) {
return ['status' => 0, 'pesan' => 'Data cuti tidak ditemukan'];
}
$alasanTolak = trim($alasanTolak);
if ($alasanTolak === '') {
return ['status' => 0, 'pesan' => 'Alasan penolakan wajib diisi.'];
}
$this->db->table('cuti')->where('id_cuti', $id)->update([
'status_cuti' => 'Rejected',
'alasan_tolak' => $alasanTolak,
]);
return ['status' => 1, 'pesan' => 'Cuti ditolak.'];
}
/**
* @return array<string, mixed>|null
*/
private function fetchPegawaiDetail(int $id): ?array
{
$row = $this->db->table('pegawai p')
->select('p.*, j.nama_jabatan, u.nama_unit_kerja, g.nama_golongan, k.nama_kantor, jd.nama_jadwal')
->join('jabatan j', 'j.id_jabatan = p.jabatan', 'left')
->join('unit_kerja u', 'u.id_unit_kerja = p.unit_kerja', 'left')
->join('golongan g', 'g.id_golongan = p.golongan_pekerjaan', 'left')
->join('kantor k', 'k.id_kantor = p.kantor', 'left')
->join('jadwal jd', 'jd.id_jadwal = p.jadwal', 'left')
->where('p.id_pegawai', $id)
->get()
->getRowArray();
if ($row !== null) {
unset($row['password'], $row['token']);
}
return $row;
}
private function applyCabangPegawaiAlias(BaseBuilder $b, string $alias, ?int $cabangKantorId): void
{
if ($cabangKantorId !== null && $cabangKantorId > 0) {
$b->where("{$alias}.kantor", $cabangKantorId);
}
}
private function pegawaiIdAllowedForCabang(int $pegawaiId, ?int $cabangKantorId): bool
{
if ($cabangKantorId === null || $cabangKantorId <= 0) {
return true;
}
return $this->db->table('pegawai')->where('id_pegawai', $pegawaiId)->where('kantor', $cabangKantorId)->countAllResults() > 0;
}
/**
* @param array<string, mixed> $row baris pegawai (key `kantor` = id_kantor)
*/
private function pegawaiRowInCabang(array $row, ?int $cabangKantorId): bool
{
if ($cabangKantorId === null || $cabangKantorId <= 0) {
return true;
}
return (int) ($row['kantor'] ?? 0) === $cabangKantorId;
}
private function cutiAllowedForCabang(int $cutiId, ?int $cabangKantorId): bool
{
if ($cabangKantorId === null || $cabangKantorId <= 0) {
return true;
}
$row = $this->db->table('cuti c')
->select('p.kantor')
->join('pegawai p', 'p.id_pegawai = c.pegawai', 'left')
->where('c.id_cuti', $cutiId)
->get()
->getRowArray();
return $row !== null && (int) ($row['kantor'] ?? 0) === $cabangKantorId;
}
private function applyPegawaiSearchFilter(BaseBuilder $b, string $search): void
{
if ($search === '') {
return;
}
$b->groupStart()
->like('p.nama_lengkap', $search)
->orLike('p.nip', $search)
->orLike('p.username', $search)
->groupEnd();
}
private function normalizeDate(mixed $v): ?string
{
if ($v === null || $v === '' || $v === '0000-00-00') {
return null;
}
$s = (string) $v;
return $s;
}
/**
* Kunci baris cuti ke huruf kecil + rapikan bentuk tanggal_cuti setelah JSON (objek/array).
*
* @param array<string, mixed> $row
*
* @return array<string, mixed>
*/
private function normalizeCutiRowArrayForApi(array $row): array
{
$row = array_change_key_case($row, CASE_LOWER);
$tc = $row['tanggal_cuti'] ?? null;
if (is_array($tc)) {
$row['tanggal_cuti'] = $tc['date'] ?? $tc['value'] ?? null;
}
return $row;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,263 @@
<?php
declare(strict_types=1);
namespace App\Services\Admin;
use App\Services\Mobile\MobileJsonService;
use CodeIgniter\Database\BaseConnection;
use Config\Database;
/**
* Login admin memakai Ion Auth CI3: `admin_users` + relasi `admin_users_groups` / `admin_groups`.
* Password: bcrypt ($2a$/$2y$) atau legacy MD5 (32 hex).
* Setelah sukses, token API ditulis ke baris pegawai "proxy" (sama seperti sebelumnya).
*/
class AdminUsersLoginService
{
protected BaseConnection $db;
public function __construct(?BaseConnection $db = null)
{
$this->db = $db ?? Database::connect();
}
/**
* @return array{
* ok: true,
* token: string,
* username: string,
* admin_user_id: int,
* group_names: list<string>,
* group_ids: list<int>
* }|array{ok: false, reason: 'skip'|'invalid'|'no_group'|'no_proxy'}
*/
/**
* Cari id_pegawai dari identifier login (username pegawai atau NIP).
*/
public function resolvePegawaiIdFromCredentials(string $username): ?int
{
$username = trim($username);
if ($username === '') {
return null;
}
$p = $this->db->table('pegawai')->select('id_pegawai')->where('username', $username)->get()->getRowArray();
if ($p !== null && ! empty($p['id_pegawai'])) {
return (int) $p['id_pegawai'];
}
$p = $this->db->table('pegawai')->select('id_pegawai')->where('nip', $username)->get()->getRowArray();
if ($p !== null && ! empty($p['id_pegawai'])) {
return (int) $p['id_pegawai'];
}
return null;
}
/**
* Pegawai yang di baris `admin_users` punya `id_pegawai` sama + aktif + punya grup Ion
* → panel memakai RBAC grup (supervisor, HRD, dll.), bukan mode pegawai panel tipis.
*
* @return array{admin_user_id: int, username: string, group_names: list<string>}|null
*/
public function findLinkedAdminForPegawaiId(int $pegawaiId): ?array
{
if ($pegawaiId <= 0 || ! $this->db->tableExists('admin_users')) {
return null;
}
if (! $this->db->fieldExists('id_pegawai', 'admin_users')) {
return null;
}
$row = $this->db->table('admin_users')
->where('id_pegawai', $pegawaiId)
->where('active', 1)
->orderBy('id', 'ASC')
->get()
->getRowArray();
if ($row === null) {
return null;
}
$userId = (int) ($row['id'] ?? 0);
if ($userId <= 0) {
return null;
}
$groups = $this->loadAdminGroupsForUser($userId);
if ($this->db->tableExists('admin_users_groups') && $groups['names'] === []) {
return null;
}
return [
'admin_user_id' => $userId,
'username' => (string) ($row['username'] ?? ''),
'group_names' => $groups['names'],
];
}
public function tryLogin(string $username, string $password): array
{
if ($username === '' || $password === '') {
return ['ok' => false, 'reason' => 'skip'];
}
if (! $this->db->tableExists('admin_users')) {
return ['ok' => false, 'reason' => 'skip'];
}
$row = $this->db->table('admin_users')
->where('username', $username)
->where('active', 1)
->get()
->getRowArray();
if ($row === null || empty($row['password'])) {
return ['ok' => false, 'reason' => 'invalid'];
}
$hash = (string) $row['password'];
if (! $this->verifyAdminPassword($password, $hash)) {
return ['ok' => false, 'reason' => 'invalid'];
}
$userId = (int) $row['id'];
$groups = $this->loadAdminGroupsForUser($userId);
if ($this->db->tableExists('admin_users_groups') && $groups === []) {
return ['ok' => false, 'reason' => 'no_group'];
}
$proxyId = $this->resolveProxyPegawaiId($groups, $row);
if ($proxyId === null) {
return ['ok' => false, 'reason' => 'no_proxy'];
}
$mobile = new MobileJsonService($this->db);
$token = $mobile->issueTokenForPegawaiId($proxyId);
if ($token === null) {
return ['ok' => false, 'reason' => 'no_proxy'];
}
$this->db->table('admin_users')->where('id', $userId)->update([
'last_login' => time(),
]);
return [
'ok' => true,
'token' => $token,
'username' => $username,
'admin_user_id' => $userId,
'group_names' => $groups['names'],
'group_ids' => $groups['ids'],
];
}
/**
* @return array{names: list<string>, ids: list<int>}
*/
private function loadAdminGroupsForUser(int $userId): array
{
if (! $this->db->tableExists('admin_users_groups') || ! $this->db->tableExists('admin_groups')) {
return ['names' => [], 'ids' => []];
}
$rows = $this->db->table('admin_users_groups ug')
->select('g.id, g.name')
->join('admin_groups g', 'g.id = ug.group_id', 'inner')
->where('ug.user_id', $userId)
->orderBy('g.id', 'ASC')
->get()
->getResultArray();
$names = [];
$ids = [];
foreach ($rows as $r) {
$ids[] = (int) ($r['id'] ?? 0);
$names[] = (string) ($r['name'] ?? '');
}
return ['names' => $names, 'ids' => $ids];
}
/**
* Proxy pegawai untuk token API. Bisa diarahkan per grup (mis. HRD) lewat .env.
*
* @param array{names: list<string>, ids: list<int>} $groups
* @param array<string, mixed>|null $adminRow Baris admin_users (untuk id_pegawai per-akun).
*/
private function resolveProxyPegawaiId(array $groups, ?array $adminRow = null): ?int
{
if ($adminRow !== null && $this->db->fieldExists('id_pegawai', 'admin_users')) {
$assigned = (int) ($adminRow['id_pegawai'] ?? 0);
if ($assigned > 0 && $this->pegawaiExists($assigned)) {
return $assigned;
}
}
$fromEnv = env('ADMIN_LOGIN_PROXY_PEGAWAI_ID');
if (is_string($fromEnv) && $fromEnv !== '') {
$id = (int) $fromEnv;
if ($id > 0 && $this->pegawaiExists($id)) {
return $id;
}
}
$hrdOnly = in_array('hrd', array_map('strtolower', $groups['names']), true)
&& ! in_array('webmaster', array_map('strtolower', $groups['names']), true);
if ($hrdOnly) {
$hrdEnv = env('ADMIN_LOGIN_PROXY_PEGAWAI_ID_HRD');
if (is_string($hrdEnv) && $hrdEnv !== '') {
$hid = (int) $hrdEnv;
if ($hid > 0 && $this->pegawaiExists($hid)) {
return $hid;
}
}
}
$super = $this->db->table('pegawai')
->select('id_pegawai')
->where('super_akses', 'true')
->orderBy('id_pegawai', 'ASC')
->limit(1)
->get()
->getRowArray();
if ($super !== null && ! empty($super['id_pegawai'])) {
return (int) $super['id_pegawai'];
}
$any = $this->db->table('pegawai')
->select('id_pegawai')
->orderBy('id_pegawai', 'ASC')
->limit(1)
->get()
->getRowArray();
if ($any !== null && ! empty($any['id_pegawai'])) {
return (int) $any['id_pegawai'];
}
return null;
}
private function verifyAdminPassword(string $plain, string $hash): bool
{
if (str_starts_with($hash, '$2y$') || str_starts_with($hash, '$2a$') || str_starts_with($hash, '$2b$')) {
return password_verify($plain, $hash);
}
if (strlen($hash) === 32 && ctype_xdigit($hash)) {
return md5($plain) === $hash;
}
return password_verify($plain, $hash);
}
private function pegawaiExists(int $id): bool
{
return $this->db->table('pegawai')->where('id_pegawai', $id)->countAllResults() > 0;
}
}

View File

@@ -0,0 +1,194 @@
<?php
declare(strict_types=1);
namespace App\Services;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\HTTP\RequestInterface;
use Config\Database;
use Config\Services;
use Throwable;
/**
* Audit trail untuk aksi admin (API `/api/admin/*` dan keamanan).
*/
class AdminAuditService
{
private const MAX_PAYLOAD_CHARS = 65535;
private BaseConnection $db;
public function __construct(?BaseConnection $db = null)
{
$this->db = $db ?? Database::connect();
}
/**
* Catat satu baris audit. `payload` disimpan sebagai JSON (disederhanakan & dibatasi panjang).
* Konteks sesi (auth_source, grup Ion) diambil dari session saat dipanggil dari request web.
*
* @param array<string, mixed> $payload
*/
public function log(string $action, array $payload = []): void
{
try {
if (! $this->db->tableExists('admin_activity_logs')) {
log_message('debug', 'AdminAuditService: tabel admin_activity_logs belum ada — jalankan migrasi.');
return;
}
$req = Services::request();
$sess = session();
$outcome = (string) ($payload['__outcome'] ?? 'success');
$body = $payload;
unset($body['__outcome']);
$row = [
'admin_user' => $this->resolveAdminUserLabel($sess, $body),
'action' => $this->truncate($action, 128),
'endpoint' => $this->truncate($req->getUri()->getPath(), 512),
'payload' => $this->encodePayload($this->enrichPayload($req, $sess, $body)),
'ip_address' => $this->truncate($req->getIPAddress(), 45),
'user_agent' => $this->truncate($req->getUserAgent()->__toString(), 512),
'auth_source' => $this->truncate((string) ($sess->get('admin_auth_source') ?? ''), 32) ?: null,
'roles_json' => $this->encodeRolesJson($sess),
'outcome' => $this->truncate($outcome, 32),
'created_at' => date('Y-m-d H:i:s'),
];
$this->db->table('admin_activity_logs')->insert($row);
} catch (Throwable $e) {
log_message('error', 'AdminAuditService::log gagal: ' . $e->getMessage());
}
}
/**
* @param array<string, mixed> $sessPayload
*/
private function resolveAdminUserLabel($sess, array $sessPayload): string
{
$u = $sess->get('admin_username');
if (is_string($u) && $u !== '') {
return $this->truncate($u, 191);
}
$actor = $sessPayload['actor'] ?? null;
if (is_array($actor)) {
$nip = (string) ($actor['nip'] ?? '');
$id = (string) ($actor['id_pegawai'] ?? '');
if ($nip !== '') {
return $this->truncate('pegawai:' . $nip, 191);
}
if ($id !== '') {
return $this->truncate('pegawai:id:' . $id, 191);
}
}
return 'unknown';
}
/**
* @param array<string, mixed> $payload
*
* @return array<string, mixed>
*/
private function enrichPayload(RequestInterface $req, $sess, array $payload): array
{
$out = $this->sanitizeForStorage($payload);
$out['_http'] = [
'method' => $req->getMethod(),
'uri' => (string) $req->getUri(),
];
$out['_session_panel'] = [
'has_admin_token' => is_string($sess->get('admin_mobile_token')) && $sess->get('admin_mobile_token') !== '',
'auth_source' => $sess->get('admin_auth_source'),
'ion_groups' => $sess->get('admin_ion_groups'),
];
return $out;
}
/**
* @param array<string, mixed> $data
*
* @return array<string, mixed>
*/
private function sanitizeForStorage(array $data): array
{
$redactKeys = ['password', 'token', 'admin_mobile_token'];
return $this->stripSensitiveRecursive($data, $redactKeys);
}
/**
* @param array<string, mixed> $data
* @param list<string> $redactKeys
*
* @return array<string, mixed>
*/
private function stripSensitiveRecursive(array $data, array $redactKeys): array
{
$out = [];
foreach ($data as $k => $v) {
$key = (string) $k;
if (in_array(strtolower($key), $redactKeys, true)) {
$out[$key] = '[redacted]';
continue;
}
if (is_array($v)) {
$out[$key] = $this->stripSensitiveRecursive($v, $redactKeys);
} elseif (is_scalar($v) || $v === null) {
$out[$key] = $v;
}
}
return $out;
}
/**
* @param array<string, mixed> $payload
*/
private function encodePayload(array $payload): ?string
{
$json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
if ($json === false) {
return null;
}
if (strlen($json) > self::MAX_PAYLOAD_CHARS) {
$json = substr($json, 0, self::MAX_PAYLOAD_CHARS - 40) . '…[truncated]';
}
return $json;
}
private function encodeRolesJson($sess): ?string
{
$g = $sess->get('admin_ion_groups');
if (! is_array($g)) {
return null;
}
$enc = json_encode(array_values($g), JSON_UNESCAPED_UNICODE);
if ($enc === false) {
return null;
}
return strlen($enc) > 16000 ? substr($enc, 0, 16000) : $enc;
}
private function truncate(string $s, int $max): string
{
if (strlen($s) <= $max) {
return $s;
}
return substr($s, 0, max(0, $max - 3)) . '...';
}
}

219
app/Services/ApiClient.php Normal file
View File

@@ -0,0 +1,219 @@
<?php
declare(strict_types=1);
namespace App\Services;
use CodeIgniter\HTTP\CURLRequest;
use Config\Services;
use Throwable;
/**
* Klien HTTP ke API internal (`/api/mobile/*` dan `/api/admin/*`).
* Controller admin web tidak mengakses DB; hanya memanggil API lewat kelas ini.
*/
class ApiClient
{
private CURLRequest $client;
public function __construct(?CURLRequest $client = null)
{
$this->client = $client ?? Services::curlrequest([
'timeout' => 30,
'http_errors' => false,
]);
}
/**
* @param array<string, scalar|null> $formData
*
* @return array{transport_ok: bool, http_code: int, json: array<string, mixed>|null, error: string|null, raw: string}
*/
public function postMobile(string $method, array $formData = []): array
{
helper(['url']);
return $this->post('api/mobile/' . ltrim($method, '/'), $formData);
}
/**
* @param array<string, scalar|null> $formData
*
* @return array{transport_ok: bool, http_code: int, json: array<string, mixed>|null, error: string|null, raw: string}
*/
public function postMobileWithToken(string $method, string $token, array $formData = []): array
{
$formData['token'] = $token;
return $this->postMobile($method, $formData);
}
/**
* GET ke `/api/admin/{path}` — token ditambahkan ke query string.
*
* @param array<string, scalar|null> $query
*
* @return array{transport_ok: bool, http_code: int, json: array<string, mixed>|null, error: string|null, raw: string}
*/
public function getAdmin(string $path, ?string $token, array $query = []): array
{
helper(['url']);
if ($token !== null && $token !== '') {
$query['token'] = $token;
}
$forward = $this->adminInternalHeaders();
if (($forward['Cookie'] ?? '') !== '' && session_status() === PHP_SESSION_ACTIVE) {
session_write_close();
}
return $this->get('api/admin/' . ltrim($path, '/'), $query, $forward);
}
/**
* POST form ke `/api/admin/{path}`.
*
* @param array<string, scalar|null> $formData
*
* @return array{transport_ok: bool, http_code: int, json: array<string, mixed>|null, error: string|null, raw: string}
*/
public function postAdmin(string $path, ?string $token, array $formData = []): array
{
helper(['url']);
if ($token !== null && $token !== '') {
$formData['token'] = $token;
}
$forward = $this->adminInternalHeaders();
if (($forward['Cookie'] ?? '') !== '' && session_status() === PHP_SESSION_ACTIVE) {
session_write_close();
}
return $this->post('api/admin/' . ltrim($path, '/'), $formData, $forward);
}
/**
* GET generik (relatif terhadap root site, mis. `api/admin/pegawai`).
*
* @param array<string, scalar|null> $query
* @param array<string, string> $extraHeaders
*
* @return array{transport_ok: bool, http_code: int, json: array<string, mixed>|null, error: string|null, raw: string}
*/
public function get(string $path, array $query = [], array $extraHeaders = []): array
{
helper(['url']);
$url = base_url(ltrim($path, '/'));
$base = $this->emptyResult();
$headers = array_merge(
['Accept' => 'application/json'],
$extraHeaders
);
try {
$response = $this->client->get($url, [
'query' => $query,
'headers' => $headers,
]);
} catch (Throwable $e) {
$base['error'] = $e->getMessage();
return $base;
}
return $this->fillFromResponse($base, $response->getStatusCode(), $response->getBody());
}
/**
* POST `application/x-www-form-urlencoded`.
*
* @param array<string, scalar|null> $formData
* @param array<string, string> $extraHeaders
*
* @return array{transport_ok: bool, http_code: int, json: array<string, mixed>|null, error: string|null, raw: string}
*/
public function post(string $path, array $formData = [], array $extraHeaders = []): array
{
helper(['url']);
$url = base_url(ltrim($path, '/'));
$base = $this->emptyResult();
$headers = array_merge(
['Accept' => 'application/json'],
$extraHeaders
);
try {
$response = $this->client->post($url, [
'form_params' => $formData,
'headers' => $headers,
]);
} catch (Throwable $e) {
$base['error'] = $e->getMessage();
return $base;
}
return $this->fillFromResponse($base, $response->getStatusCode(), $response->getBody());
}
/**
* Teruskan cookie browser ke hit internal `/api/admin/*` agar sesi panel sama.
*
* @return array<string, string>
*/
private function adminInternalHeaders(): array
{
$cookie = Services::request()->getHeaderLine('Cookie');
return $cookie !== '' ? ['Cookie' => $cookie] : [];
}
/**
* @param array<string, mixed>|null $json
*/
public static function isSuccess(?array $json): bool
{
return is_array($json) && (int) ($json['status'] ?? 0) === 1;
}
/**
* @return array{transport_ok: bool, http_code: int, json: array<string, mixed>|null, error: string|null, raw: string}
*/
private function emptyResult(): array
{
return [
'transport_ok' => false,
'http_code' => 0,
'json' => null,
'error' => null,
'raw' => '',
];
}
/**
* @param array{transport_ok: bool, http_code: int, json: array<string, mixed>|null, error: string|null, raw: string} $base
*
* @return array{transport_ok: bool, http_code: int, json: array<string, mixed>|null, error: string|null, raw: string}
*/
private function fillFromResponse(array $base, int $statusCode, string $body): array
{
$base['http_code'] = $statusCode;
$base['raw'] = $body;
$base['transport_ok'] = $statusCode === 200;
$decoded = json_decode($body, true);
if (! is_array($decoded)) {
$base['error'] = 'Respons bukan JSON objek';
return $base;
}
$base['json'] = $decoded;
return $base;
}
}

View File

@@ -0,0 +1,786 @@
<?php
namespace App\Services\Mobile;
use CodeIgniter\Database\BaseConnection;
use Config\Database;
use Exception;
/**
* Port logika bisnis dari CI3 `application/controllers/Json.php`.
* Respons struktur disamakan dengan legacy untuk kompatibilitas aplikasi mobile.
*
* TODO (fase berikutnya): pecah per agregat (PresensiService, CutiService), tambahkan transaksi,
* perbaiki keamanan (MD5 → password_hash, token → JWT) setelah cutover klien.
*/
class MobileJsonService
{
protected BaseConnection $db;
/** @var array<int, string> */
private array $hariIndo = [
1 => 'Senin',
2 => 'Selasa',
3 => 'Rabu',
4 => 'Kamis',
5 => 'Jumat',
6 => 'Sabtu',
7 => 'Minggu',
];
public function __construct(?BaseConnection $db = null)
{
$this->db = $db ?? Database::connect();
}
public function loginWToken(string $token): array
{
$data = [
'status' => 0,
'pesan' => '',
];
$pegawai = $this->db->table('pegawai')->where('token', $token)->get()->getRow();
if ($pegawai) {
unset($pegawai->username, $pegawai->password, $pegawai->token);
$this->db->table('pegawai')->where('id_pegawai', $pegawai->id_pegawai)->update([
'last_login' => date('Y-m-d H:i:s'),
]);
$data['status'] = 1;
}
return $data;
}
public function login(string $user, string $pass): array
{
$data = [
'status' => 0,
'pesan' => 'Username atau Password tidak sesuai',
];
$pegawai = $this->db->table('pegawai')
->where('username', $user)
->where('password', md5($pass))
->get()
->getRow();
if ($pegawai) {
unset($pegawai->username, $pegawai->password, $pegawai->token);
$token = md5((string) $pegawai->id_pegawai) . $this->generateRandomString(15);
$this->db->table('pegawai')->where('id_pegawai', $pegawai->id_pegawai)->update([
'token' => $token,
'last_login' => date('Y-m-d H:i:s'),
]);
$data['status'] = 1;
$data['pesan'] = 'Selamat datang';
$data['token'] = $token;
}
return $data;
}
/**
* Terbitkan token API mobile untuk pegawai (id_pegawai), seperti setelah login sukses.
* Dipakai saat login admin lewat tabel admin_users (proxy token ke pegawai tertentu).
*/
public function issueTokenForPegawaiId(int $id): ?string
{
$pegawai = $this->db->table('pegawai')->where('id_pegawai', $id)->get()->getRow();
if ($pegawai === null) {
return null;
}
$token = md5((string) $pegawai->id_pegawai) . $this->generateRandomString(15);
$this->db->table('pegawai')->where('id_pegawai', $id)->update([
'token' => $token,
'last_login' => date('Y-m-d H:i:s'),
]);
return $token;
}
public function profil(string $token): array
{
$data = [
'status' => 0,
'pesan' => '',
];
$pegawai = $this->db->table('pegawai')
->select('*, COALESCE(tanggal_lahir, \'0000-00-00\') as tanggal_lahir', false)
->where('token', $token)
->limit(1)
->get()
->getRow();
if (! $pegawai) {
return $data;
}
unset($pegawai->username, $pegawai->password, $pegawai->token);
$pegawai->kantor = $this->db->table('kantor')->where('id_kantor', $pegawai->kantor)->limit(1)->get()->getRow();
$pegawai->jabatan = $this->db->table('jabatan')->where('id_jabatan', $pegawai->jabatan)->limit(1)->get()->getRow();
$pegawai->unit_kerja = $this->db->table('unit_kerja')->where('id_unit_kerja', $pegawai->unit_kerja)->limit(1)->get()->getRow();
$pegawai->lembur = $this->db->table('lembur')->where('pegawai', $pegawai->id_pegawai)->where('tanggal_lembur', date('Y-m-d'))->limit(1)->get()->getRow();
$dilapangan = $this->db->table('dilapangan')->where('pegawai', $pegawai->id_pegawai)->limit(1)->get()->getRow();
$pegawai->dilapangan = $dilapangan ? true : false;
$hari = (int) date('N');
$pre_in = $hari . '_in';
$pre_out = $hari . '_out';
$jadwal_ar = [
'hari' => $this->hariIndo[$hari],
'masuk' => '',
'pulang' => '',
'istirahat' => '',
'toleransi_masuk' => '0',
'toleransi_pulang' => '0',
'libur' => true,
];
$libur_perusahaan = $this->db->table('libur')->where('tanggal_libur', date('Y-m-d'))->limit(1)->get()->getRow();
if ($libur_perusahaan) {
$jadwal_ar['ket_libur'] = 'Libur: ' . $libur_perusahaan->keterangan_libur;
} else {
$cuti = $this->db->table('cuti')
->where('pegawai', $pegawai->id_pegawai)
->where('tanggal_cuti', date('Y-m-d'))
->where('status_cuti', 'Approve')
->limit(1)
->get()
->getRow();
if ($cuti) {
$jadwal_ar['ket_libur'] = 'Cuti: ' . $cuti->alasan_cuti;
} else {
$jadwal = $this->db->table('jadwal')->where('id_jadwal', $pegawai->jadwal)->limit(1)->get()->getRow();
if ($jadwal) {
$jadwal_ar['masuk'] = $jadwal->{$pre_in};
$jadwal_ar['pulang'] = $jadwal->{$pre_out};
$jadwal_ar['istirahat'] = '12:00';
$jadwal_ar['toleransi_masuk'] = $jadwal->toleransi_terlambat;
$jadwal_ar['toleransi_pulang'] = $jadwal->toleransi_pulang_cepat;
$jadwal_ar['libur'] = false;
$jadwal_ar['ket_libur'] = '';
} else {
$jadwal_ar['ket_libur'] = 'Tidak ada jadwal. Hubungi Petugas';
}
}
}
$pegawai->jadwal = $jadwal_ar;
$data['status'] = 1;
$data['pegawai'] = $pegawai;
return $data;
}
public function saveCuti(string $token, string $nama_photo, string $img, string $tanggal, string $alasan, string $tipe): array
{
$data = [
'status' => 0,
'pesan' => '',
];
$pegawai = $this->db->table('pegawai')->where('token', $token)->limit(1)->get()->getRow();
if (! $pegawai) {
return $data;
}
$dir = $this->ensureUploadDir('dokcuti');
$image = base64_decode($img);
$image_name = uniqid((string) mt_rand(), true);
$filename = $image_name . '-' . $nama_photo;
if ($image === false || $image === '' || file_put_contents($dir . DIRECTORY_SEPARATOR . $filename, $image) === false) {
$data['pesan'] = 'Photo Dokumen GAGAL upload';
return $data;
}
$this->db->table('cuti')->insert([
'pegawai' => $pegawai->id_pegawai,
'tanggal_cuti' => $tanggal,
'tipe_cuti' => $tipe,
'alasan_cuti' => $alasan,
'status_cuti' => 'Waiting',
'alasan_tolak' => '',
]);
$id = (int) $this->db->insertID();
$this->db->table('cuti_dokumen')->insert([
'cuti' => $id,
'dokumen' => $filename,
]);
$data['status'] = 1;
$data['pesan'] = 'Photo Dokumen berhasil di upload';
return $data;
}
/**
* @param int|string|null $id
*/
public function batalkanCuti(string $token, $id): array
{
$data = [
'status' => 0,
'pesan' => '',
];
$pegawai = $this->db->table('pegawai')->where('token', $token)->limit(1)->get()->getRow();
if (! $pegawai) {
return $data;
}
$this->db->table('cuti')->where('pegawai', $pegawai->id_pegawai)->where('id_cuti', $id)->update([
'status_cuti' => 'Cancelled',
]);
$data['status'] = 1;
$data['pesan'] = "Ajuan di batalkan {$id} - {$pegawai->id_pegawai}";
return $data;
}
public function saveAktifitas(string $token, string $nama_photo, string $img, string $tanggal, string $deksripsi): array
{
$data = [
'status' => 0,
'pesan' => '',
];
$pegawai = $this->db->table('pegawai')->where('token', $token)->limit(1)->get()->getRow();
if (! $pegawai) {
return $data;
}
$dir = $this->ensureUploadDir('aktifitas');
$image = base64_decode($img);
$image_name = uniqid((string) mt_rand(), true);
$filename = $image_name . '-' . $nama_photo;
if ($image === false || $image === '' || file_put_contents($dir . DIRECTORY_SEPARATOR . $filename, $image) === false) {
$data['pesan'] = 'Photo Kegiatan GAGAL upload';
return $data;
}
$this->db->table('aktifitas_harian')->insert([
'pegawai' => $pegawai->id_pegawai,
'image' => $filename,
'deskripsi' => $deksripsi,
'waktu_aktifitas' => $tanggal,
]);
$data['status'] = 1;
$data['pesan'] = 'Photo Kegiatan berhasil di upload';
return $data;
}
public function saveMasuk(string $token, string $nama_photo, string $img, string $lat, string $lng, string $jarak): array
{
$data = [
'status' => 0,
'pesan' => 'Tidak ada jadwal kerja',
];
$pegawai = $this->db->table('pegawai')->where('token', $token)->limit(1)->get()->getRow();
if (! $pegawai) {
return $data;
}
$jadwal = $this->db->table('jadwal')->where('id_jadwal', $pegawai->jadwal)->limit(1)->get()->getRow();
if (! $jadwal) {
return $data;
}
$dir = $this->ensureUploadDir('absen' . DIRECTORY_SEPARATOR . 'masuk');
$image = base64_decode($img);
$image_name = uniqid((string) mt_rand(), true);
$filename = $image_name . '-' . $nama_photo;
if ($image === false || $image === '' || file_put_contents($dir . DIRECTORY_SEPARATOR . $filename, $image) === false) {
$data['pesan'] = 'Photo Kehadiran GAGAL upload';
return $data;
}
$hari = (int) date('N');
$pre_in = $hari . '_in';
$masuk_jadwal = date('Y-m-d') . ' ' . $jadwal->{$pre_in};
$jam_masuk = strtotime($masuk_jadwal);
$jam_toleransi = strtotime($masuk_jadwal) + ((int) $jadwal->toleransi_terlambat * 60);
$jam_sekarang = time();
if ($jam_sekarang < $jam_masuk) {
$ket_masuk = 'Sesuai jadwal';
} elseif ($jam_sekarang >= $jam_masuk && $jam_sekarang <= $jam_toleransi) {
$ket_masuk = 'Terlambat';
} else {
$ket_masuk = 'Sangat terlambat';
}
$this->db->table('presensi')->where('tanggal', date('Y-m-d'))->where('pegawai', $pegawai->id_pegawai)->update([
'jam_masuk' => date('Y-m-d H:i:s'),
'ket_masuk' => $ket_masuk,
'photo_masuk' => $filename,
'lat_masuk' => $lat,
'lng_masuk' => $lng,
'jarak_masuk' => $jarak,
]);
$data['status'] = 1;
$data['pesan'] = 'Photo Kehadiran berhasil di upload';
return $data;
}
public function savePulang(string $token, string $nama_photo, string $img, string $lat, string $lng, string $jarak): array
{
$data = [
'status' => 0,
'pesan' => 'Tidak ada jadwal kerja',
];
$pegawai = $this->db->table('pegawai')->where('token', $token)->limit(1)->get()->getRow();
if (! $pegawai) {
return $data;
}
$jadwal = $this->db->table('jadwal')->where('id_jadwal', $pegawai->jadwal)->limit(1)->get()->getRow();
if (! $jadwal) {
return $data;
}
$dir = $this->ensureUploadDir('absen' . DIRECTORY_SEPARATOR . 'pulang');
$image = base64_decode($img);
$image_name = uniqid((string) mt_rand(), true);
$filename = $image_name . '-' . $nama_photo;
if ($image === false || $image === '' || file_put_contents($dir . DIRECTORY_SEPARATOR . $filename, $image) === false) {
$data['pesan'] = 'Photo Kehadiran GAGAL upload';
return $data;
}
$wibNow = new \DateTimeImmutable('now', new \DateTimeZone('Asia/Jakarta'));
$hari = (int) $wibNow->format('N');
$pre_out = $hari . '_out';
$jadwal_pulang = $wibNow->format('Y-m-d') . ' ' . $jadwal->{$pre_out};
$jam_pulang = strtotime($jadwal_pulang);
$jam_toleransi = strtotime($jadwal_pulang) - ((int) $jadwal->toleransi_terlambat * 60);
$jam_sekarang = $wibNow->getTimestamp();
if ($jam_sekarang < $jam_toleransi) {
$data['pesan'] = 'Belum waktunya Pulang, waktu pulang anda adalah pukul ' . $jadwal->{$pre_out} . '. Jika anda memerlukan untuk pulang cepat, silahkan hubungi Operator';
return $data;
}
if ($jam_sekarang >= $jam_toleransi && $jam_sekarang <= $jam_pulang) {
$ket_pulang = 'Pulang Cepat';
} else {
$ket_pulang = 'Sesuai jadwal';
}
$this->db->table('presensi')->where('tanggal', $wibNow->format('Y-m-d'))->where('pegawai', $pegawai->id_pegawai)->update([
'jam_pulang' => $wibNow->format('Y-m-d H:i:s'),
'ket_pulang' => $ket_pulang,
'photo_pulang' => $filename,
'lat_pulang' => $lat,
'lng_pulang' => $lng,
'jarak_pulang' => $jarak,
]);
$data['status'] = 1;
$data['pesan'] = 'Photo Kehadiran berhasil di upload';
return $data;
}
public function saveIstirahat(string $token, string $mulai, string $selesai): array
{
$data = [
'status' => 0,
'pesan' => 'Tidak ada jadwal kerja',
];
$pegawai = $this->db->table('pegawai')->where('token', $token)->limit(1)->get()->getRow();
if (! $pegawai) {
return $data;
}
$jadwal = $this->db->table('jadwal')->where('id_jadwal', $pegawai->jadwal)->limit(1)->get()->getRow();
if (! $jadwal) {
return $data;
}
$ist = null;
if ($mulai !== '') {
$ist = [
'mulai_istirahat' => $mulai,
'beres_istirahat' => $mulai,
];
}
if ($selesai !== '') {
$ist = [
'beres_istirahat' => $selesai,
'is_istirahat' => 1,
];
}
if ($ist === null) {
return $data;
}
$this->db->table('presensi')->where('tanggal', date('Y-m-d'))->where('pegawai', $pegawai->id_pegawai)->update($ist);
$data['status'] = 1;
$data['pesan'] = 'berhasil disimpan';
return $data;
}
public function presensiToday(string $token): array
{
$data = [
'status' => 0,
'pesan' => '',
];
$pegawai = $this->db->table('pegawai')->select('id_pegawai, jadwal')->where('token', $token)->limit(1)->get()->getRow();
if (! $pegawai) {
return $data;
}
$presensi = $this->db->table('presensi')->where('tanggal', date('Y-m-d'))->where('pegawai', $pegawai->id_pegawai)->limit(1)->get()->getRow();
if (! $presensi) {
$jadwal = $this->db->table('jadwal')->where('id_jadwal', $pegawai->jadwal)->get()->getRow();
$ins = [
'pegawai' => $pegawai->id_pegawai,
'tanggal' => date('Y-m-d'),
'jadwal' => serialize($jadwal),
'jam_masuk' => null,
'ket_masuk' => '',
'photo_masuk' => '',
'jam_pulang' => null,
'ket_pulang' => '',
'photo_pulang' => '',
'mulai_istirahat' => null,
'beres_istirahat' => null,
'is_istirahat' => '0',
'lat_masuk' => '0',
'lng_masuk' => '0',
'lat_pulang' => '0',
'lng_pulang' => '0',
'jarak_masuk' => '0',
'jarak_pulang' => '0',
];
$this->db->table('presensi')->insert($ins);
$id = (int) $this->db->insertID();
$ins['id_presensi'] = $id . '.';
$presensi = (object) $ins;
}
$data['status'] = 1;
$data['data'] = $presensi;
return $data;
}
public function presensi(string $token): array
{
$data = [
'status' => 0,
'pesan' => '',
];
$pegawai = $this->db->table('pegawai')->select('id_pegawai, jadwal')->where('token', $token)->limit(1)->get()->getRow();
if (! $pegawai) {
return $data;
}
$presensi = $this->db->table('presensi')->where('pegawai', $pegawai->id_pegawai)->orderBy('tanggal', 'DESC')->limit(20)->get()->getResult();
if ($presensi) {
$data['status'] = 1;
$data['data'] = $presensi;
}
return $data;
}
public function daftarToday(string $token): array
{
$data = [
'status' => 0,
'pesan' => '',
];
$pegawai = $this->db->table('pegawai')->select('id_pegawai, jadwal')->where('token', $token)->limit(1)->get()->getRow();
if (! $pegawai) {
return $data;
}
$today = date('Y-m-d');
$presensi = $this->db->table('pegawai')
->join('jabatan', 'id_jabatan=jabatan', 'left')
->join('presensi', 'id_pegawai=pegawai AND tanggal = ' . $this->db->escape($today), 'left', false)
->where('id_pegawai !=', $pegawai->id_pegawai)
->where('id_presensi IS NOT NULL', null, false)
->orderBy('jam_masuk', 'DESC')
->orderBy('nama_lengkap')
->get()
->getResult();
if ($presensi) {
$data['status'] = 1;
$data['data'] = $presensi;
}
return $data;
}
public function berita(string $token, $dari, $jumlah): array
{
if ($dari === '' || $dari === null) {
$dari = 0;
}
if ($jumlah === '' || $jumlah === null) {
$jumlah = 10;
}
$dari = (int) $dari;
$jumlah = (int) $jumlah;
$data = [
'status' => 0,
'pesan' => '',
];
$pegawai = $this->db->table('pegawai')->select('id_pegawai')->where('token', $token)->limit(1)->get()->getRow();
if (! $pegawai) {
return $data;
}
$berita = $this->db->table('berita')->orderBy('tanggal', 'DESC')->limit($jumlah, $dari)->get()->getResult();
$data['status'] = 1;
$data['data'] = $berita;
return $data;
}
public function cuti(string $token, $dari, $jumlah): array
{
if ($dari === '' || $dari === null) {
$dari = 0;
}
if ($jumlah === '' || $jumlah === null) {
$jumlah = 25;
}
$dari = (int) $dari;
$jumlah = (int) $jumlah;
$data = [
'status' => 0,
'pesan' => '',
];
$pegawai = $this->db->table('pegawai')->select('id_pegawai')->where('token', $token)->limit(1)->get()->getRow();
if (! $pegawai) {
return $data;
}
$cuti = $this->db->table('cuti')->where('pegawai', $pegawai->id_pegawai)->orderBy('tanggal_cuti', 'DESC')->limit($jumlah, $dari)->get()->getResult();
if ($cuti) {
foreach ($cuti as $v) {
$v->dokumen = $this->db->table('cuti_dokumen')->select('dokumen')->where('cuti', $v->id_cuti)->get()->getResult();
}
}
$data['status'] = 1;
$data['data'] = $cuti;
return $data;
}
public function lembur(string $token, $dari, $jumlah): array
{
if ($dari === '' || $dari === null) {
$dari = 0;
}
if ($jumlah === '' || $jumlah === null) {
$jumlah = 25;
}
$dari = (int) $dari;
$jumlah = (int) $jumlah;
$data = [
'status' => 0,
'pesan' => '',
];
$pegawai = $this->db->table('pegawai')->select('id_pegawai')->where('token', $token)->limit(1)->get()->getRow();
if (! $pegawai) {
return $data;
}
$rows = $this->db->table('lembur')->where('pegawai', $pegawai->id_pegawai)->orderBy('tanggal_lembur', 'DESC')->limit($jumlah, $dari)->get()->getResult();
$data['status'] = 1;
$data['data'] = $rows;
return $data;
}
public function libur(string $token): array
{
$data = [
'status' => 0,
'pesan' => '',
];
$pegawai = $this->db->table('pegawai')->select('id_pegawai')->where('token', $token)->limit(1)->get()->getRow();
if (! $pegawai) {
return $data;
}
$rows = $this->db->table('libur')->orderBy('tanggal_libur', 'DESC')->get()->getResult();
$data['status'] = 1;
$data['data'] = $rows;
return $data;
}
public function aktifitas(string $token, $dari, $jumlah): array
{
if ($dari === '' || $dari === null) {
$dari = 0;
}
if ($jumlah === '' || $jumlah === null) {
$jumlah = 25;
}
$dari = (int) $dari;
$jumlah = (int) $jumlah;
$data = [
'status' => 0,
'pesan' => '',
];
$pegawai = $this->db->table('pegawai')->select('id_pegawai')->where('token', $token)->limit(1)->get()->getRow();
if (! $pegawai) {
return $data;
}
$rows = $this->db->table('aktifitas_harian')->where('pegawai', $pegawai->id_pegawai)->orderBy('waktu_aktifitas', 'DESC')->limit($jumlah, $dari)->get()->getResult();
$data['status'] = 1;
$data['data'] = $rows;
return $data;
}
public function savePp(string $token, string $nama_photo, string $img): array
{
$data = [
'status' => 0,
'pesan' => 'Tidak ada jadwal kerja',
];
$pegawai = $this->db->table('pegawai')->where('token', $token)->limit(1)->get()->getRow();
if (! $pegawai) {
return $data;
}
$dir = $this->ensureUploadDir('pengguna');
$image = base64_decode($img);
$image_name = uniqid((string) mt_rand(), true);
$filename = $image_name . '-' . $nama_photo;
if ($image === false || $image === '' || file_put_contents($dir . DIRECTORY_SEPARATOR . $filename, $image) === false) {
$data['pesan'] = 'Photo Kehadiran GAGAL upload';
return $data;
}
if ($pegawai->photo !== '' && $pegawai->photo !== null) {
try {
$photoPath = $dir . DIRECTORY_SEPARATOR . $pegawai->photo;
if (is_file($photoPath)) {
unlink($photoPath);
}
} catch (Exception $e) {
}
}
$this->db->table('pegawai')->where('id_pegawai', $pegawai->id_pegawai)->update([
'photo' => $filename,
]);
$data['status'] = 1;
$data['pesan'] = 'Photo Profil berhasil di upload';
return $data;
}
public function savePassword(string $token, string $passlama, string $passbaru): array
{
$data = [
'status' => 0,
'pesan' => '-',
];
$pegawai = $this->db->table('pegawai')->where('token', $token)->limit(1)->get()->getRow();
if (! $pegawai) {
return $data;
}
if (md5($passlama) == $pegawai->password) {
$this->db->table('pegawai')->where('id_pegawai', $pegawai->id_pegawai)->update([
'password' => md5($passbaru),
]);
$data['status'] = 1;
$data['pesan'] = 'Password berhasil di ubah';
} else {
$data['pesan'] = 'Password lama tidak sesuai, silahkan coba lagi';
}
return $data;
}
private function generateRandomString(int $length = 10): string
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
// Sengaja memakai rand() seperti CI3 agar pola token kompatibel.
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
private function ensureUploadDir(string $relativeUnderUploads): string
{
$base = FCPATH . 'assets' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $relativeUnderUploads);
if (! is_dir($base)) {
mkdir($base, 0755, true);
}
return $base;
}
}

0
app/ThirdParty/.gitkeep vendored Normal file
View File

View File

@@ -0,0 +1,42 @@
<?= $this->extend('layouts/auth') ?>
<?= $this->section('title') ?>Login Admin<?= $this->endSection() ?>
<?= $this->section('content') ?>
<div class="rounded-2xl border border-gray-200 bg-white p-8 shadow-md shadow-gray-200/50 sm:p-10">
<div class="mb-6 text-center">
<h1 class="text-xl font-semibold text-gray-900">Masuk ke admin</h1>
<p class="mt-2 text-sm text-gray-500">Gunakan akun pegawai (sama seperti aplikasi mobile) atau akun panel administrator. Sesi menyimpan token API.</p>
</div>
<?php if (session()->getFlashdata('message')) : ?>
<div class="mb-4 rounded-2xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800 shadow-sm" role="status">
<?= esc(session()->getFlashdata('message')) ?>
</div>
<?php endif ?>
<?php if (session()->getFlashdata('error')) : ?>
<div class="mb-4 rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800 shadow-sm" role="alert">
<?= esc(session()->getFlashdata('error')) ?>
</div>
<?php endif ?>
<form action="<?= site_url('admin/login') ?>" method="post" class="space-y-5">
<?= csrf_field() ?>
<div>
<label for="username" class="mb-1.5 block text-sm font-medium text-gray-700">Username</label>
<input type="text" name="username" id="username" value="<?= esc(old('username')) ?>"
class="h-11 w-full rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm text-gray-800 shadow-sm placeholder:text-gray-400 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20"
autocomplete="username" required>
</div>
<div>
<label for="password" class="mb-1.5 block text-sm font-medium text-gray-700">Password</label>
<input type="password" name="password" id="password"
class="h-11 w-full rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm text-gray-800 shadow-sm placeholder:text-gray-400 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20"
autocomplete="current-password" required>
</div>
<button type="submit" class="flex w-full items-center justify-center rounded-lg bg-blue-600 px-4 py-3 text-sm font-semibold text-white shadow-sm transition hover:bg-blue-700">
Login
</button>
</form>
</div>
<?= $this->endSection() ?>

View File

@@ -0,0 +1,110 @@
<?= $this->extend('layouts/main') ?>
<?= $this->section('title') ?>Detail Cuti<?= $this->endSection() ?>
<?php
$cuti = is_array($bundle) ? ($bundle['cuti'] ?? null) : null;
$dok = is_array($bundle) ? ($bundle['dokumen'] ?? []) : [];
$cuti = is_array($cuti) ? $cuti : [];
$st = (string) ($cuti['status_cuti'] ?? '');
$badgeClass = match ($st) {
'Approve' => 'bg-emerald-50 text-emerald-800 ring-1 ring-emerald-100',
'Rejected' => 'bg-red-50 text-red-800 ring-1 ring-red-100',
'Waiting' => 'bg-amber-50 text-amber-900 ring-1 ring-amber-100',
'Cancelled' => 'bg-gray-100 text-gray-600 ring-1 ring-gray-200',
default => 'bg-gray-100 text-gray-700 ring-1 ring-gray-200',
};
?>
<?= $this->section('content') ?>
<div class="mx-auto max-w-3xl space-y-6">
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 class="text-2xl font-semibold tracking-tight text-gray-900">Detail cuti</h1>
<?php if ($cuti !== []) : ?>
<p class="mt-2"><span class="inline-flex rounded-full px-3 py-1 text-xs font-semibold <?= $badgeClass ?>"><?= esc($st !== '' ? $st : '—') ?></span></p>
<?php endif ?>
</div>
<a href="<?= site_url('admin/cuti') ?>" class="inline-flex items-center justify-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2.5 text-sm font-medium text-gray-800 shadow-sm hover:bg-gray-50">
<i class="fa-solid fa-arrow-left text-xs text-gray-500"></i> Kembali ke daftar
</a>
</div>
<?= view('layouts/partials/admin_alert', ['errors' => $errors ?? []]) ?>
<?php if ($cuti !== []) : ?>
<section class="rounded-2xl border border-gray-200 bg-white p-6 shadow-sm">
<h2 class="text-xs font-semibold uppercase tracking-wide text-gray-500">Ringkasan</h2>
<dl class="mt-4 grid gap-4 text-sm sm:grid-cols-2">
<div class="sm:col-span-2">
<dt class="text-xs font-medium text-gray-500">Pegawai</dt>
<dd class="mt-1 font-semibold text-gray-900"><?= esc((string) ($cuti['nama_lengkap'] ?? '')) ?> <span class="font-normal text-gray-500">· NIP <?= esc((string) ($cuti['nip'] ?? '')) ?></span></dd>
</div>
<div>
<dt class="text-xs font-medium text-gray-500">Tanggal cuti</dt>
<dd class="mt-1 font-medium text-gray-900"><?= esc(cuti_tanggal_label_from_row($cuti)) ?></dd>
</div>
<div>
<dt class="text-xs font-medium text-gray-500">Tipe</dt>
<dd class="mt-1 text-gray-800"><?= esc((string) ($cuti['tipe_cuti'] ?? '')) ?></dd>
</div>
<div class="sm:col-span-2">
<dt class="text-xs font-medium text-gray-500">Alasan</dt>
<dd class="mt-1 text-gray-800"><?= esc((string) ($cuti['alasan_cuti'] ?? '')) ?></dd>
</div>
<?php if ($st === 'Rejected' && ! empty($cuti['alasan_tolak'])) : ?>
<div class="sm:col-span-2 rounded-xl border border-red-100 bg-red-50/50 p-3">
<dt class="text-xs font-semibold text-red-800">Alasan tolak</dt>
<dd class="mt-1 text-sm text-red-900"><?= esc((string) $cuti['alasan_tolak']) ?></dd>
</div>
<?php endif ?>
</dl>
</section>
<?php if ($dok !== []) : ?>
<section class="rounded-2xl border border-gray-200 bg-white p-6 shadow-sm">
<h2 class="text-sm font-semibold text-gray-900">Dokumen</h2>
<ul class="mt-3 space-y-2 text-sm">
<?php foreach ($dok as $d) : ?>
<?php if (! is_array($d)) {
continue;
} ?>
<?php $fn = (string) ($d['dokumen'] ?? ''); ?>
<?php if ($fn !== '') : ?>
<li>
<a href="<?= esc(site_url('admin/cuti/dokumen/' . rawurlencode($fn))) ?>" target="_blank" rel="noopener noreferrer" class="inline-flex items-center gap-2 font-medium text-blue-600 hover:text-blue-800">
<i class="fa-regular fa-file text-gray-400"></i> <?= esc($fn) ?>
</a>
</li>
<?php endif ?>
<?php endforeach ?>
</ul>
</section>
<?php endif ?>
<?php if ($st === 'Waiting') : ?>
<section class="rounded-2xl border border-gray-200 bg-white p-6 shadow-sm space-y-5">
<h2 class="text-sm font-semibold text-gray-900">Persetujuan</h2>
<form method="post" action="<?= site_url('admin/cuti/approve/' . $id) ?>" class="flex flex-wrap gap-2">
<?= csrf_field() ?>
<button type="submit" class="inline-flex rounded-lg bg-emerald-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-emerald-700">Setujui (Approve)</button>
</form>
<form method="post" action="<?= site_url('admin/cuti/reject/' . $id) ?>" class="space-y-3 border-t border-gray-100 pt-5">
<?= csrf_field() ?>
<label class="block text-xs font-medium text-gray-600">Tolak — alasan wajib</label>
<textarea name="alasan_tolak" rows="3" required class="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500" placeholder="Jelaskan alasan penolakan"><?= esc(old('alasan_tolak') ?? '') ?></textarea>
<button type="submit" class="inline-flex rounded-lg bg-red-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-red-700">Tolak (Reject)</button>
</form>
</section>
<?php endif ?>
<?php else : ?>
<div class="rounded-2xl border border-gray-200 bg-white p-6 shadow-sm">
<?= view('layouts/partials/empty_state', [
'icon' => 'fa-circle-question',
'title' => 'Cuti tidak ditemukan',
'hint' => 'ID tidak valid atau data sudah tidak tersedia.',
]) ?>
</div>
<?php endif ?>
</div>
<?= $this->endSection() ?>

View File

@@ -0,0 +1,117 @@
<?= $this->extend('layouts/main') ?>
<?= $this->section('title') ?>Data Cuti<?= $this->endSection() ?>
<?php
$rows = is_array($payload) ? ($payload['rows'] ?? []) : [];
$total = is_array($payload) ? (int) ($payload['total'] ?? 0) : 0;
$totalPage = is_array($payload) ? max(1, (int) ($payload['total_page'] ?? 1)) : 1;
$curPage = is_array($payload) ? (int) ($payload['page'] ?? $page) : $page;
$statusOpts = ['' => 'Semua', 'Waiting' => 'Waiting', 'Approve' => 'Approve', 'Rejected' => 'Rejected', 'Cancelled' => 'Cancelled'];
?>
<?= $this->section('content') ?>
<div class="space-y-6">
<div>
<h1 class="text-2xl font-semibold tracking-tight text-gray-900">Data cuti pegawai</h1>
<p class="mt-1 max-w-2xl text-sm text-gray-500">Filter menurut status dan lakukan persetujuan atau penolakan dari sini.</p>
</div>
<?= view('layouts/partials/admin_alert', ['errors' => $errors ?? []]) ?>
<form method="get" action="<?= site_url('admin/cuti') ?>" class="rounded-2xl border border-gray-200 bg-white p-5 shadow-sm">
<div class="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
<div>
<label class="block text-xs font-medium text-gray-600">Status</label>
<select name="status" class="mt-1 min-w-[12rem] rounded-lg border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500">
<?php foreach ($statusOpts as $val => $lab) : ?>
<option value="<?= esc($val) ?>" <?= ($status === $val) ? 'selected' : '' ?>><?= esc($lab) ?></option>
<?php endforeach ?>
</select>
</div>
<div class="flex flex-wrap items-center gap-2">
<button type="submit" class="inline-flex items-center justify-center rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-700">Terapkan</button>
<a href="<?= site_url('admin/cuti') ?>" class="inline-flex items-center justify-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-800 shadow-sm hover:bg-gray-50">Semua status</a>
</div>
</div>
</form>
<section class="overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-sm">
<div class="border-b border-gray-200 px-5 py-4">
<h2 class="text-base font-semibold text-gray-900">Daftar permohonan</h2>
<p class="mt-0.5 text-xs text-gray-500">Hijau = disetujui · kuning = menunggu · merah = ditolak.</p>
</div>
<?php if ($rows === []) : ?>
<div class="p-6">
<?= view('layouts/partials/empty_state', [
'icon' => 'fa-plane-departure',
'title' => 'Tidak ada permohonan cuti',
'hint' => 'Pilih status lain atau kembali ke Semua status untuk melihat seluruh riwayat.',
]) ?>
</div>
<?php else : ?>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200 text-sm">
<thead class="bg-gray-50 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">
<tr>
<th class="px-4 py-3">Pegawai</th>
<th class="px-4 py-3">Tanggal</th>
<th class="px-4 py-3">Tipe</th>
<th class="px-4 py-3">Status</th>
<th class="px-4 py-3"></th>
</tr>
</thead>
<tbody class="divide-y divide-gray-100">
<?php foreach ($rows as $c) : ?>
<?php if (! is_array($c)) {
continue;
} ?>
<?php
$st = (string) ($c['status_cuti'] ?? '');
$badge = match ($st) {
'Approve' => 'bg-emerald-50 text-emerald-800 ring-1 ring-emerald-100',
'Rejected' => 'bg-red-50 text-red-800 ring-1 ring-red-100',
'Waiting' => 'bg-amber-50 text-amber-900 ring-1 ring-amber-100',
'Cancelled' => 'bg-gray-100 text-gray-600 ring-1 ring-gray-200',
default => 'bg-gray-100 text-gray-700 ring-1 ring-gray-200',
};
?>
<tr class="transition-colors hover:bg-gray-50">
<td class="px-4 py-2.5">
<div class="font-medium text-gray-900"><?= esc((string) ($c['nama_lengkap'] ?? '')) ?></div>
<div class="text-xs text-gray-500"><?= esc((string) ($c['nip'] ?? '')) ?></div>
</td>
<td class="whitespace-nowrap px-4 py-2.5 text-gray-800"><?= esc(cuti_tanggal_label_from_row($c)) ?></td>
<td class="px-4 py-2.5 text-gray-700"><?= esc((string) ($c['tipe_cuti'] ?? '')) ?></td>
<td class="px-4 py-2.5">
<span class="inline-flex rounded-full px-2.5 py-0.5 text-xs font-semibold <?= $badge ?>"><?= esc($st) ?></span>
</td>
<td class="whitespace-nowrap px-4 py-2.5">
<a href="<?= site_url('admin/cuti/detail/' . (int) ($c['id_cuti'] ?? 0)) ?>" class="mr-2 text-xs font-semibold text-blue-600 hover:text-blue-800">Detail</a>
<?php if ($st === 'Waiting') : ?>
<form method="post" action="<?= site_url('admin/cuti/approve/' . (int) ($c['id_cuti'] ?? 0)) ?>" class="inline" onsubmit="return confirm('Setujui permohonan ini?');">
<?= csrf_field() ?>
<button type="submit" class="text-xs font-semibold text-emerald-700 hover:text-emerald-900 hover:underline">Approve</button>
</form>
<?php endif ?>
</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</div>
<?php endif ?>
<div class="flex flex-col gap-3 border-t border-gray-200 bg-gray-50/80 px-5 py-3 text-xs text-gray-600 sm:flex-row sm:items-center sm:justify-between">
<span>Total: <strong class="text-gray-900"><?= number_format($total, 0, ',', '.') ?></strong></span>
<div class="flex flex-wrap gap-2">
<?php if ($curPage > 1) : ?>
<a class="inline-flex rounded-lg border border-gray-200 bg-white px-3 py-1.5 font-medium text-gray-800 shadow-sm hover:bg-gray-50" href="<?= site_url('admin/cuti?' . http_build_query(['status' => $status, 'page' => $curPage - 1])) ?>">Sebelumnya</a>
<?php endif ?>
<?php if ($curPage < $totalPage) : ?>
<a class="inline-flex rounded-lg border border-gray-200 bg-white px-3 py-1.5 font-medium text-gray-800 shadow-sm hover:bg-gray-50" href="<?= site_url('admin/cuti?' . http_build_query(['status' => $status, 'page' => $curPage + 1])) ?>">Berikutnya</a>
<?php endif ?>
</div>
</div>
</section>
</div>
<?= $this->endSection() ?>

Some files were not shown because too many files have changed in this diff Show More