| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415 |
- <?php
- // 전체 배열의 키를 대문자, 소문자로 변경해서 반환한다.
- function arrayChangeKeyCaseRecursive($arr = [], $case = CASE_LOWER): string
- {
- return array_map(function ($item) use ($case) {
- if (is_array($item)){
- $item = arrayChangeKeyCaseRecursive($item, $case);
- }
- return $item;
- }, array_change_key_case($arr, $case));
- }
- // Request Url
- function currentURL(): string
- {
- $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http");
- $host = (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost');
- $query = (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '');
- return sprintf("%s://%s%s", $protocol, $host, $query);
- }
- // 데이터 단위 변환
- function byteFormat($num, $precision = 1): string
- {
- if ($num >= 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 '<span class="text-danger">Off</span>';
- case 1:
- return '<span class="text-success">On</span>';
- 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)) ? '<span class="text-success">사용가능</span>' : '<span class="text-danger">Г—</span>';
- }
- }
- // 리눅스 시스템 보기 - 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 . '<script type="module">';
- // 아이프레임 주소 허용여부 결정
- $html .= sprintf('var whiteIframe = "%s";', $whiteIframe);
- // 이모티콘 사용여부
- $html .= sprintf('var useEmoticon = "%s";', ($emoticonYN ? 'Y' : 'N'));
- $html .= '</script>';
- define('LOAD_DHTML_EDITOR_JS', true);
- }
- $html .= '<textarea';
- $html .= sprintf(' class="tinymce-editor %s"', $className);
- if($name) {
- $html .= sprintf(' name="%s"', $name);
- }
- if($id) {
- $html .= sprintf(' id="%s"', $id);
- }
- if($placeholder) {
- $html .= sprintf(' placeholder="%s"', $placeholder);
- }
- if ($rows) {
- $html .= sprintf(' rows="%s"', $rows);
- }
- $html .= ('>' . htmlspecialchars($content) . '</textarea>');
- 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;
- }
- // 날짜와 시간에 <br/>, \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), '<br/>'); // 태그 제거, 공백 제거
- $msg = preg_replace('/<br[^>]*>/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('<script>alert("%s");</script>', $msg)
- , 200, ['Content-Type', 'text/javascript']);
- }
- }
- // 로그인 확인
- function loginCheck(string $callback = null): Illuminate\Http\Response|\Illuminate\Contracts\Routing\ResponseFactory
- {
- $s = "<script>";
- $s .= "if (confirm(\"로그인 후 이용하실 수 있습니다.\\n로그인 화면으로 이동하시겠습니까?\")) {";
- $s .= "location.href = \"" . route('login') . "?callback=" . urlencode(url($_SERVER['REQUEST_URI']) ?? $callback) . "\";";
- $s .= "}else{";
- $s .= "history.go(-1);";
- $s .= "}";
- $s .= "</script>";
- return response($s, 200, ['Content-Type', 'text/javascript']);
- }
- // Alert 후 창 닫음
- function alertClose(string $msg): Illuminate\Http\Response|\Illuminate\Contracts\Routing\ResponseFactory
- {
- $s = "<script>";
- $s .= "alert(\"$msg\");";
- $s .= "self.close();";
- $s .= "window.close();";
- $s .= "</script>";
- 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.*src=\"(.*)\".*><\/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 <iframe ...></iframe> 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', '<span style="background: #ff9632;color: #000;">$0</span>', $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);
- }
|