<?php
namespace App\Helpers;
use App\Models\Permission;
use App\Models\Role;
use App\Models\Menu;
use App\Models\Profil;
use Carbon\Carbon;
use CURLFile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class Helper
{
public static function getTotalPay($data)
{
$total = 0;
foreach ($data->langganan->where('status', 'paket aktif') as $key => $value) {
$total += $value->paket->getTotal() - ($value->paket->getTotal() * ($value->affiliate->potongan / 100));
}
return $total;
}
public static function formatUangPendek($angka)
{
if ($angka >= 1000000) {
// Bagi dengan 1 juta dan format dengan 1 desimal jika perlu
$hasil = number_format($angka / 1000000, fmod($angka, 1000000) == 0 ? 0 : 1, ',', '.') . ' jt';
} elseif ($angka >= 1000) {
// Bagi dengan 1 ribu dan format tanpa desimal
$hasil = number_format($angka / 1000, 0, ',', '.') . ' K';
} else {
// Jika di bawah 1000, tampilkan angkanya saja
$hasil = number_format($angka, 0, ',', '.');
}
return 'Rp. ' . $hasil;
}
public static function splitHarga($harga, $item = null)
{
// Format angka dengan pemisah ribuan
$harga_format = number_format((int) $harga, 0, ',', '.');
// Ambil 3 digit terakhir
$tiga_digit_terakhir = substr($harga_format, -3);
// Ambil sisa digit di depannya
$sisa_digit = substr($harga_format, 0, -3);
if ($item != null) {
if ($item->created_at != null) {
$tiga_digit_terakhir = $item->created_at->format("Hi");
} else {
$tiga_digit_terakhir = $item->id;
}
$tiga_digit_terakhir = substr($tiga_digit_terakhir, -3);
}
$tiga_digit_terakhir = sprintf("%03d", $tiga_digit_terakhir);
$tiga_digit_terakhir = substr($tiga_digit_terakhir, -3);
return [$sisa_digit, $tiga_digit_terakhir];
}
public static function createDomain($domain, $tgl_selesai)
{
$subdomain = $domain . ".fixmate.id";
$subdomain_dir = env('DOMAIN_LIST_DIR', base_path('subdomains'));
$base_app_path = env('BASE_APP_PATH', base_path('subdomains/demo.fixmate.id'));
//copy folder from base_app_path to subdomain_dir
$subdomain_path = $subdomain_dir . '/' . $domain . '.fixmate.id';
if (!file_exists($subdomain_path)) {
mkdir($subdomain_path, 0755, true);
}
$source_path = $base_app_path;
$destination_path = $subdomain_path;
// Check if the source directory exists
if (!is_dir($source_path)) {
return false;
}
// Create the destination directory if it doesn't exist
if (!is_dir($destination_path)) {
mkdir($destination_path, 0755, true);
}
// Get the contents of the source directory
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source_path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
// Iterate over the contents and copy them to the destination
foreach ($iterator as $item) {
$dest = $destination_path . DIRECTORY_SEPARATOR . $iterator->getSubPathname();
if ($item->isDir()) {
if (!is_dir($dest)) {
mkdir($dest, 0755, true);
}
} else {
//create the directory if it does not exist
// $destination_dir = dirname($destination_path);
// if (!is_dir($destination_dir)) {
// mkdir($destination_dir, 0755, true);
// }
copy($item, $dest);
}
}
$databaseName = "aplikasiposinfo_" . $domain . '_fixmate_id';
$char = 'abcdefghijklmnopqrstuvwxyz';
//userMysql is random characters from $char + _fixmate_id
$userMysql = str_shuffle(substr($char, 0, 8)) . '_fixmate_id';
$passMysql = bin2hex(random_bytes(8));
$connection = DB::connection('mysql_admin');
$connection->statement("CREATE DATABASE IF NOT EXISTS `{$databaseName}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
$connection->statement("CREATE USER IF NOT EXISTS '{$userMysql}'@'localhost' IDENTIFIED BY '{$passMysql}'");
$connection->statement("GRANT ALL PRIVILEGES ON `{$databaseName}`.* TO '{$userMysql}'@'localhost'");
//$connection->statement("FLUSH PRIVILEGES");
$username = $domain . "@fixmate.id";
//random password
$password = bin2hex(random_bytes(8));
// update .env file
$envFilePath = $subdomain_path . '/.env';
if (file_exists($envFilePath)) {
$envContent = file_get_contents($envFilePath);
$envContent = preg_replace('/^APP_URL=.*/m', 'APP_URL=https://' . $domain . '.fixmate.id', $envContent);
$envContent = preg_replace('/^APP_NAME=.*/m', 'APP_NAME=' . $domain, $envContent);
//set APP_ENV to development
$envContent = preg_replace('/^APP_ENV=.*/m', 'APP_ENV=development', $envContent);
//set DEFAULT_USER_EMAIL and DEFAULT_USER_PASSWORD
$envContent = preg_replace('/^DEFAULT_USER_EMAIL=.*/m', 'DEFAULT_USER_EMAIL=' . $username, $envContent);
$envContent = preg_replace('/^DEFAULT_USER_PASSWORD=.*/m', 'DEFAULT_USER_PASSWORD=' . $password, $envContent);
//set COUNTDOWN
$countdown = $tgl_selesai ? Carbon::parse($tgl_selesai)->format('Y-m-d H:i:s') : date('Y-m-d H:i:s', strtotime('+1 month'));
$envContent = preg_replace('/^COUNTDOWN=.*/m', 'COUNTDOWN="' . $countdown . '"', $envContent);
//set DATABASE_NAME, DATABASE_USERNAME, DATABASE_PASSWORD
$envContent = preg_replace('/^DB_DATABASE=.*/m', 'DB_DATABASE=' . $databaseName, $envContent);
$envContent = preg_replace('/^DB_USERNAME=.*/m', 'DB_USERNAME=' . $userMysql, $envContent);
$envContent = preg_replace('/^DB_PASSWORD=.*/m', 'DB_PASSWORD=' . $passMysql, $envContent);
file_put_contents($envFilePath, $envContent);
}
//run artisan key:generate inside subdomain_path
$artisanCommand = 'php ' . $subdomain_path . '/artisan key:generate';
$process = proc_open($artisanCommand, [
0 => ["pipe", "r"], // stdin
1 => ["pipe", "w"], // stdout
2 => ["pipe", "w"], // stderr
], $pipes);
//close and log result
if (is_resource($process)) {
$output = stream_get_contents($pipes[1]);
$errors = stream_get_contents($pipes[2]);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
$result = proc_close($process); // Close the process
// Log the output
Log::info('Artisan key:generate command executed for ' . $subdomain . ': ' . $result);
if ($result == 1) {
Log::error($errors);
} else {
Log::info($output);
}
} else {
Log::error('Failed to execute artisan key:generate command for ' . $subdomain);
}
//run artisan optimize:clear
$artisanCommand = 'php ' . $subdomain_path . '/artisan optimize:clear';
$process = proc_open($artisanCommand, [
0 => ["pipe", "r"], // stdin
1 => ["pipe", "w"], // stdout
2 => ["pipe", "w"], // stderr
], $pipes);
if (is_resource($process)) {
$output = stream_get_contents($pipes[1]);
$errors = stream_get_contents($pipes[2]);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
$result = proc_close($process); // Close the process
// Log the output
Log::info('Artisan optimize:clear command executed for ' . $subdomain . ': ' . $result);
if ($result == 1) {
Log::error($errors);
} else {
Log::info($output);
}
} else {
Log::error('Failed to execute artisan optimize:clear command for ' . $subdomain);
}
$virtualHostConfigDir = base_path("virtual_host.example");
$configDirTarget = env('SERVER_CONFIG_DIR', base_path('server-config'));
$isLinux = stripos(PHP_OS, 'Linux') === 0;
//copy virtual host config to server config dir
if (file_exists($virtualHostConfigDir) && $isLinux) {
// $configContent = file_get_contents($virtualHostConfigDir);
// $configContent = str_replace('{domain}', $domain, $configContent);
// $configFilePath = $configDirTarget . '/' . $domain . '.conf';
// $originalConfig = $subdomain_path . '/' . $domain . '.conf';
// file_put_contents($originalConfig, $configContent);
$logFile = sys_get_temp_dir() . '/' . uniqid('vhost-log-') . '.txt';
touch($logFile);
chmod($logFile, 0666); // Make it world-writable and readable
$command = "sudo -n /usr/local/bin/create_vhost.sh " . escapeshellarg($subdomain). " ".escapeshellarg($logFile)." > /dev/null 2>&1 &";
$process = proc_open($command, [
0 => ["pipe", "r"], // stdin
1 => ["pipe", "w"], // stdout
2 => ["pipe", "w"], // stderr
], $pipes);
//close and log result
if (is_resource($process)) {
// fwrite($pipes[0], "qm6j7fFnMfrN" . "\n");
fclose($pipes[0]);
//$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
//$errors = stream_get_contents($pipes[2]);
fclose($pipes[2]);
$result = proc_close($process); // Close the process
// Log the output
Log::info('Virtual host config created for ' . $domain . ': ' . $result);
// if ($result == 1) {
// Log::error($errors);
// } else {
// Log::info($output);
// }
} else {
Log::error('Failed to create virtual host config for ' . $domain);
}
//request get to https://$subdomain/optimize , /migrate and /seed
// $optimizeUrl = 'https://' . $subdomain . '/optimize';
// $migrateUrl = 'https://' . $subdomain . '/migrate';
// $seedUrl = 'https://' . $subdomain . '/seed';
// $client = new \GuzzleHttp\Client();
// try {
// $client->get($optimizeUrl);
// $client->get($migrateUrl);
// $client->get($seedUrl);
// } catch (\Exception $e) {
// Log::error('Failed to run optimize, migrate, or seed for ' . $subdomain . ': ' . $e->getMessage());
// }
//set APP_ENV to production
// $envContent = file_get_contents($envFilePath);
// $envContent = preg_replace('/^APP_ENV=.*/m', 'APP_ENV=production', $envContent);
// file_put_contents($envFilePath, $envContent);
}
return [
'subdomain' => $subdomain,
'database' => $databaseName,
'username' => $username,
'password' => $password,
'countdown' => $countdown,
'log_file' => @$logFile ?? null,
];
}
public static function deleteDomain($domain)
{
$subdomain = $domain . ".fixmate.id";
$subdomain_dir = env('DOMAIN_LIST_DIR', base_path('subdomains'));
//copy folder from base_app_path to subdomain_dir
$subdomain_path = $subdomain_dir . '/' . $domain . '.fixmate.id';
$envFilePath = $subdomain_path . '/.env';
$command = "sudo -n /usr/local/bin/delete_vhost.sh " . escapeshellarg($subdomain)." > /dev/null 2>&1 &";
$process = proc_open($command, [
0 => ["pipe", "r"], // stdin
1 => ["pipe", "w"], // stdout
2 => ["pipe", "w"], // stderr
], $pipes);
//close and log result
if (is_resource($process)) {
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
$result = proc_close($process); // Close the process
Log::info('Virtual host config deleted for ' . $domain . ': ' . $result);
} else {
Log::error('Failed to delete virtual host config for ' . $domain);
}
//get database name from .env file
if (file_exists($envFilePath)) {
$envContent = file_get_contents($envFilePath);
$connection = DB::connection('mysql_admin');
preg_match('/^DB_DATABASE=(.*)$/m', $envContent, $matches);
if (isset($matches[1])) {
$databaseName = trim($matches[1]);
// Drop the database
$connection->statement("DROP DATABASE IF EXISTS `{$databaseName}`");
}
preg_match('/^DB_USERNAME=(.*)$/m', $envContent, $matches);
if (isset($matches[1])) {
$userMysql = trim($matches[1]);
// Drop the user
$connection->statement("DROP USER IF EXISTS `{$userMysql}`@'localhost'");
}
}
return true;
}
public static function checkStatusCreatedDomain($logFile){
//check status based on the log file
if (!file_exists($logFile)) {
return [
'status' => 'not_found',
'message' => 'Log file does not exist',
];
}
$logContent = file_get_contents($logFile);
if (strpos($logContent, 'SCRIPT_COMPLETE') !== false) {
return [
'status' => 'success',
'message' => 'Domain created successfully',
];
} elseif (strpos($logContent, 'SCRIPT_ERROR') !== false) {
return [
'status' => 'error',
'message' => 'Error occurred during domain creation',
];
} else {
return [
'status' => 'pending',
'message' => $logContent,
];
}
}
}
Anons79 File Manager Version 1.0, Coded By Anons79
Email: [email protected]