= 1000000000000) {
$num = round($num / 1099511627776, $precision);
$unit = 'TB';
} elseif ($num >= 1000000000) {
$num = round($num / 1073741824, $precision);
$unit = 'GB';
} elseif ($num >= 1000000) {
$num = round($num / 1048576, $precision);
$unit = 'MB';
} elseif ($num >= 1000) {
$num = round($num / 1024, $precision);
$unit = 'KB';
} else {
$unit = 'Bytes';
return number_format($num) . ' ' . $unit;
}
return number_format($num, $precision) . ' ' . $unit;
}
// 데이터 단위 지정 변환
function byteToFormat($bytes = 0, $unit = "", $decimals = 0): string
{
$units = ['B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8];
$value = 0;
if ($bytes > 0) {
if (!array_key_exists($unit, $units)) {
$pow = floor(log($bytes) / log(1024));
$unit = array_search($pow, $units);
}
$value = ($bytes / pow(1024, floor($units[$unit])));
}
if (!is_numeric($decimals) || $decimals < 0) {
$decimals = 2;
}
return sprintf('%.' . $decimals . 'f ' . $unit, $value);
}
// 상태 보기
function show($varName): string
{
switch ($result = get_cfg_var($varName)) {
case 0:
return 'Off';
case 1:
return 'On';
default:
return $result;
}
}
// 리눅스 시스템 보기 - 파일권한
function isFun($funName = ""): string
{
if (!$funName || trim($funName) == '' || preg_match('~[^a-z0-9\_]+~i', $funName, $tmp)) {
return '알수없음';
} else {
return (false !== function_exists($funName)) ? '사용가능' : 'Г—';
}
}
// 리눅스 시스템 보기 - CPU 모델
function GetCoreInformation(): array
{
$data = @file('/proc/stat');
$cores = [];
if($data) {
foreach ($data as $line) {
if (preg_match('/^cpu[0-9]/', $line)) {
$info = explode(' ', $line);
$cores[] = ['user' => $info[1], 'nice' => $info[2], 'sys' => $info[3], 'idle' => $info[4], 'iowait' => $info[5], 'irq' => $info[6], 'softirq' => $info[7]];
}
}
}
return $cores;
}
// 리눅스 시스템 보기 CPU 속도
function GetCpuPercentages($stat1 = [], $stat2 = []): array
{
$cpus = [];
if (count($stat1) !== count($stat2)) {
return $cpus;
}
for ($i = 0, $l = count($stat1); $i < $l; $i++) {
$dif = [];
$dif['user'] = ($stat2[$i]['user'] - $stat1[$i]['user']);
$dif['nice'] = ($stat2[$i]['nice'] - $stat1[$i]['nice']);
$dif['sys'] = ($stat2[$i]['sys'] - $stat1[$i]['sys']);
$dif['idle'] = ($stat2[$i]['idle'] - $stat1[$i]['idle']);
$dif['iowait'] = ($stat2[$i]['iowait'] - $stat1[$i]['iowait']);
$dif['irq'] = ($stat2[$i]['irq'] - $stat1[$i]['irq']);
$dif['softirq'] = ($stat2[$i]['softirq'] - $stat1[$i]['softirq']);
$total = array_sum($dif);
$cpu = [];
foreach ($dif as $x => $y) {
$cpu[$x] = round($y / $total * 100, 2);
}
$cpus['cpu' . $i] = $cpu;
}
return $cpus;
}
// 현재 URL 이 대상 URL 과 같다면 active 상태
function activeUrl($segment = ''): string
{
return (request()->is($segment) ? 'active' : '');
}
// 관리자 설정값 조회
function configs($item = '', $default = ''): string|int|null
{
$config = cache('config-meta');
if($item) {
$ret = (property_exists($config, $item) ? $config->{$item} : $default);
}else{
$ret = $config;
}
return $ret;
}
// 게시판 에디터 출력
function htmlEditor($name = '', $content = '', $className = '', $isDhtmlEditor = true, $emoticonYN = true, $placeholder = "", $rows = 0, $id = ''): string
{
// TINYMCE 에디터 추가
$html = "";
if ($isDhtmlEditor && !defined('LOAD_DHTML_EDITOR_JS'))
{
// tinymce iframe 허용
$whiteIframe = configs('white_iframe');
$whiteIframe = preg_replace("/[\r|\n|\r\n]+/", ",", $whiteIframe);
$whiteIframe = preg_replace("/\s+/", "", $whiteIframe);
$html .= PHP_EOL . '';
define('LOAD_DHTML_EDITOR_JS', true);
}
$html .= '');
return $html;
}
// 관리자 Form Submit 정보 attributes 와 맵핑
function mapAdminAttr(array $rules, array $posts): array
{
foreach(array_keys($rules) as $field) {
if(array_key_exists($field, $posts)) {
continue;
}
$posts[$field] = 0;
}
return $posts;
}
// FreeBSD 값 조회
function getKey($keyName): bool
{
return doCommand('sysctl', "-n $keyName");
}
// FreeBSD 시스템 명령 실행
function doCommand($commandName, $args): bool
{
$buffer = "";
if (false === ($command = findCommand($commandName))) {
return false;
}
if ($fp = @popen("$command $args", 'r')) {
while (!@feof($fp)) {
$buffer .= @fgets($fp, 4096);
}
return trim($buffer);
}
return false;
}
// FreeBSD 명령어 지정 조회
function findCommand($commandName)
{
$path = ['/bin', '/sbin', '/usr/bin', '/usr/sbin', '/usr/local/bin', '/usr/local/sbin'];
foreach ($path as $p) {
if (@is_executable("$p/$commandName")) {
return "$p/$commandName";
}
}
return false;
}
// 날짜와 시간에
, \n 추가
function dateBr($date = null, $default = ''): string
{
return ($date ? date('Y-m-d <\b\r /> H:i:s', strtotime($date)) : $default);
}
// Alert 띄우기
function alert(string $msg, string|null $url = "", bool $redirect = true): Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse|Illuminate\Http\Response|\Illuminate\Contracts\Routing\ResponseFactory
{
$msg = preg_replace('/(\r\n|\r|\n)/', '\n', addslashes($msg)); // 줄바꿈 되도록 출력
$msg = strip_tags(trim($msg), '
'); // 태그 제거, 공백 제거
$msg = preg_replace('/
]*>/i', '\n\n', $msg); // br 태그를 \n로 개행 alert 에서 다음줄로 하기 위함.
if ($redirect) {
if ($url) {
return redirect($url)->withErrors($msg)->withInput();
} else {
return back()->withErrors($msg)->withInput();
}
}else{
return response(
sprintf('', $msg)
, 200, ['Content-Type', 'text/javascript']);
}
}
// 로그인 확인
function loginCheck(string $callback = null): Illuminate\Http\Response|\Illuminate\Contracts\Routing\ResponseFactory
{
$s = "";
return response($s, 200, ['Content-Type', 'text/javascript']);
}
// Alert 후 창 닫음
function alertClose(string $msg): Illuminate\Http\Response|\Illuminate\Contracts\Routing\ResponseFactory
{
$s = "";
return response($s, 200, ['Content-Type', 'text/javascript']);
}
// Send socket
function getSock(string $url): string
{
// host 와 uri 를 분리
$host = "";
$get = "";
if (preg_match("/http:\/\/([a-zA-Z0-9_\-\.]+)([^<]*)/", $url, $res)) {
$host = $res[1];
$get = $res[2];
}
// 80번 포트로 소캣접속 시도
$fp = fsockopen($host, 80, $n, $s, 30);
if (empty($fp)) {
die($s . ' (' . $n . ")\n");
} else {
fputs($fp, "GET $get HTTP/1.0\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "\r\n");
$header = '';
// header 와 content 를 분리한다.
while (trim($buffer = fgets($fp, 1024)) !== '') {
$header .= $buffer;
}
while (!feof($fp)) {
$buffer .= fgets($fp, 1024);
}
}
fclose($fp);
// content 만 return 한다.
return $buffer;
}
// 휴대폰 번호 조회
function getTelNumber($phone, $hyphen = 1): string
{
if ($hyphen) {
$preg = "$1-$2-$3";
} else {
$preg = "$1$2$3";
}
$phone = str_replace('-', '', trim($phone));
return preg_replace(
"/^(01[016789])([0-9]{3,4})([0-9]{4})$/",
$preg,
$phone
);
}
// 수행 측정시간
function getTime(): float
{
$t = explode(' ', microtime());
return (float)$t[0] + (float)$t[1];
}
/**
* iframe tag 조회
*/
function getIframeTag($string = '', $onlySrc = false)
{
preg_match('/<\/iframe>/isU', $string, $matches);
if ($onlySrc) {
return (isset($matches[1])) ? $matches[1] : ""; // the src part. (http://www.youtube.com/embed/IIYeKGNNNf4?rel=0)
} else {
return (isset($matches[0])) ? $matches[0] : ""; // only the part
}
}
/*
* 이미지 인지 여부
*/
function isImage($path = ''): int
{
return intval(in_array(getimagesize($path)[2], [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP]));
}
/*
* 문자 검색 후 강조
*/
function highlight($search, $str): string
{
return (!is_null($search)) ? preg_replace( '#' . preg_quote($search,'#') . '#iu', '$0', $str) : $str;
}
/*
* 모든 공백 제거
*/
function aTrim($str): string
{
return preg_replace('/\s+/', '', $str);
}
/*
* 목록 시작 번호
* currentItems: same as limit
* currentPage: floor(start / limit)
* totalPages: ceil(totalItems / limit)
* last: totalPages * limit
* previous: (currentPage-1) * limit
* next: (currentPage+1) * limit
*/
function listNum(int $total, int $page, int $perPage): int
{
return (($listNum = ($total - ($page - 1) * $perPage)) > 0 ? $listNum : $total);
}
/*
* 단말기 구분으로 레이아웃 처리
*/
function layout(string $viewPath): string
{
return (DEVICE_TYPE != DEVICE_TYPE_1 ? ('mobile.' . $viewPath) : 'desktop.' . $viewPath);
}