초기 커밋: 5130 레거시 시스템

- URL 하드코딩 → .env APP_URL 기반 동적 URL로 변경
- DB 연결 하드코딩 → .env 기반으로 변경
- MySQL strict mode DATE 오류 수정
This commit is contained in:
2025-12-10 20:14:31 +09:00
commit aca1767eb9
6728 changed files with 1863265 additions and 0 deletions

14
notice1/_request.php Normal file
View File

@@ -0,0 +1,14 @@
<?php
$num = isset($_REQUEST["num"]) ? $_REQUEST["num"] : '';
$id = isset($_REQUEST["id"]) ? $_REQUEST["id"] : '';
$name = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
$subject = isset($_REQUEST["subject"]) ? $_REQUEST["subject"] : '';
$content = isset($_REQUEST["content"]) ? $_REQUEST["content"] : '';
$regist_day = isset($_REQUEST["regist_day"]) ? $_REQUEST["regist_day"] : '';
$hit = isset($_REQUEST["hit"]) ? $_REQUEST["hit"] : '';
$is_html = isset($_REQUEST["is_html"]) ? $_REQUEST["is_html"] : '';
$noticecheck = isset($_REQUEST["noticecheck"]) ? $_REQUEST["noticecheck"] : '';
$searchtext = isset($_REQUEST["searchtext"]) ? $_REQUEST["searchtext"] : '';
?>

13
notice1/_row.php Normal file
View File

@@ -0,0 +1,13 @@
<?php
$num = $row["num"];
$id = $row["id"];
$name = $row["name"];
$subject = $row["subject"];
$content = $row["content"];
$regist_day = $row["regist_day"];
$hit = $row["hit"];
$is_html = $row["is_html"];
$noticecheck = $row["noticecheck"];
$searchtext = $row["searchtext"];
?>

47
notice1/delete.php Normal file
View File

@@ -0,0 +1,47 @@
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/session.php'; // 세션 파일 포함
header("Content-Type: application/json"); //json을 사용하기 위해 필요한 구문
$num=$_REQUEST["num"];
$tablename=$_REQUEST["tablename"];
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();
// 첨부파일 삭제
try{
$pdo->beginTransaction();
$sql1 = "delete from {$DB}.picuploads where parentnum = ? and tablename = ? ";
$stmh1 = $pdo->prepare($sql1);
$stmh1->bindValue(1,$num, PDO::PARAM_STR);
$stmh1->bindValue(2,$tablename, PDO::PARAM_STR);
$stmh1->execute();
$pdo->commit();
} catch (Exception $ex) {
$pdo->rollBack();
print "오류: ".$Exception->getMessage();
}
try{
$pdo->beginTransaction();
$sql = "delete from {$DB}.{$tablename} where num = ?";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1,$num,PDO::PARAM_STR);
$stmh->execute();
$pdo->commit();
} catch (Exception $ex) {
$pdo->rollBack();
print "오류: ".$Exception->getMessage();
}
//각각의 정보를 하나의 배열 변수에 넣어준다.
$data = array(
"num" => $num
);
//json 출력
echo(json_encode($data, JSON_UNESCAPED_UNICODE));
?>

24
notice1/delete_ripple.php Normal file
View File

@@ -0,0 +1,24 @@
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
$num=$_REQUEST["num"];
$ripple_num=$_REQUEST["ripple_num"];
$tablename=$_REQUEST["tablename"]; //tablename 이름
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();
try{
$pdo->beginTransaction();
$sql = "delete from {$DB}.{$tablename}_ripple where num = ?"; //db만 수정
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1,$ripple_num,PDO::PARAM_STR);
$stmh->execute();
$pdo->commit();
header("Location:" . $WebSite . "notice1/view.php?tablename=$tablename&num=$num");
} catch (Exception $ex) {
$pdo->rollBack();
print "오류: ".$Exception->getMessage();
}
?>

105
notice1/insert.php Normal file
View File

@@ -0,0 +1,105 @@
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
header("Content-Type: application/json"); //json을 사용하기 위해 필요한 구문 받는측에서 필요한 정보임 ajax로 보내는 쪽에서 type : json
// 임시저장된 첨부파일을 확정하기 위해 검사하기
isset($_REQUEST["timekey"]) ? $timekey=$_REQUEST["timekey"] : $timekey=''; // 신규데이터에 생성할때 임시저장키
if(isset($_REQUEST["mode"])) //modify_form에서 호출할 경우
$mode=$_REQUEST["mode"];
else
$mode="";
if(isset($_REQUEST["tablename"]))
$tablename=$_REQUEST["tablename"];
else
$tablename="";
include '_request.php';
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();
if ($mode == "modify") {
try {
$pdo->beginTransaction();
$sql = "update " . $DB . "." . $tablename . " set subject=?, content=?, is_html=?, noticecheck=?, searchtext=? where num=?";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $subject, PDO::PARAM_STR);
$stmh->bindValue(2, $content, PDO::PARAM_LOB);
$stmh->bindValue(3, $is_html, PDO::PARAM_STR);
$stmh->bindValue(4, $noticecheck, PDO::PARAM_STR);
$stmh->bindValue(5, $searchtext, PDO::PARAM_STR);
$stmh->bindValue(6, $num, PDO::PARAM_INT);
$stmh->execute();
$pdo->commit();
} catch (PDOException $Exception) {
$pdo->rollBack();
print "오류: " . $Exception->getMessage();
}
} else {
if ($is_html == "y") {
$content = htmlspecialchars($content);
}
try {
$pdo->beginTransaction();
$sql = "insert into " . $DB . "." . $tablename . " (id, name, subject, content, regist_day, hit, is_html, noticecheck, searchtext) ";
$sql .= "values(?, ?, ?, ?, now(), 0, ?, ?, ?)";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $_SESSION["userid"], PDO::PARAM_STR);
$stmh->bindValue(2, $_SESSION["name"], PDO::PARAM_STR);
$stmh->bindValue(3, $subject, PDO::PARAM_STR);
$stmh->bindValue(4, $content, PDO::PARAM_LOB);
$stmh->bindValue(5, $is_html, PDO::PARAM_STR);
$stmh->bindValue(6, $noticecheck, PDO::PARAM_STR);
$stmh->bindValue(7, $searchtext, PDO::PARAM_STR);
$stmh->execute();
$pdo->commit();
} catch (PDOException $Exception) {
$pdo->rollBack();
print "오류: " . $Exception->getMessage();
}
}
if ($mode != "modify") {
// 신규데이터인경우 num을 추출한 후 view로 보여주기
$sql = "select * from " . $DB . "." . $tablename . " order by num desc limit 1";
try {
$stmh = $pdo->query($sql);
$rowNum = $stmh->rowCount();
$row = $stmh->fetch(PDO::FETCH_ASSOC);
$num = $row["num"];
} catch (PDOException $Exception) {
print "오류: " . $Exception->getMessage();
}
// 신규데이터인 경우 첨부파일/첨부이미지 추가한 것이 있으면 parentid 변경해줌
// 신규데이터인경우 num을 추출한 후 view로 보여주기
try{
$pdo->beginTransaction();
$sql = "update ".$DB.".picuploads set parentnum=? where parentnum=? ";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $num, PDO::PARAM_STR);
$stmh->bindValue(2, $timekey, PDO::PARAM_STR);
$stmh->execute();
$pdo->commit();
} catch (PDOException $Exception) {
$pdo->rollBack();
print "오류: ".$Exception->getMessage();
}
}
$data = [
'num' => $num,
'tablename' => $tablename
];
echo json_encode($data, JSON_UNESCAPED_UNICODE);
?>

28
notice1/insert_ripple.php Normal file
View File

@@ -0,0 +1,28 @@
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
$num=$_REQUEST["num"];
$tablename=$_REQUEST["tablename"]; //tablename 이름
$ripple_content=$_REQUEST["ripple_content"];
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();
try{
$pdo->beginTransaction();
$sql = "insert into {$DB}.{$tablename}_ripple (parent, id, name, content, regist_day) ";
$sql.= "values(?, ?, ?, ?,now())";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $num, PDO::PARAM_STR);
$stmh->bindValue(2, $_SESSION["userid"], PDO::PARAM_STR);
$stmh->bindValue(3, $_SESSION["name"], PDO::PARAM_STR);
$stmh->bindValue(4, $ripple_content, PDO::PARAM_STR);
$stmh->execute();
$pdo->commit();
header("Location:" . $WebSite . "{$tablename}/view.php?tablename=$tablename&num=$num");
} catch (PDOException $Exception) {
$pdo->rollBack();
print "오류: ".$Exception->getMessage();
}
?>

225
notice1/list.php Normal file
View File

@@ -0,0 +1,225 @@
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
// 첫 화면 표시 문구
$title_message = '공지사항';
if(!isset($_SESSION["level"]) || $_SESSION["level"]>5) {
sleep(1);
header("Location:" . $WebSite . "login/login_form.php");
exit;
}
include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php';
?>
<title> <?=$title_message?> </title>
</head>
<body>
<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader1.php'); ?>
<?php
$tablename = "notice1";
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();
if(isset($_REQUEST["mode"]))
$mode=$_REQUEST["mode"];
else
$mode="";
if(isset($_REQUEST["search"])) // search 쿼리스트링 값 할당 체크
$search=$_REQUEST["search"];
else
$search="";
if($mode=="search"){
if(!$search) {
$sql ="select * from " . $DB . "." . $tablename . " order by num desc ";
}
$sql="select * from " . $DB . "." . $tablename . " where name like '%$search%' or subject like '%$search%' or regist_day like '%$search%' or searchtext like '%$search%' order by num desc ";
} else {
$sql="select * from " . $DB . "." . $tablename . " order by num desc";
}
try{
$stmh = $pdo->query($sql); // 검색조건에 맞는글 stmh
$total_row=$stmh->rowCount();
} catch (PDOException $Exception) {
print "오류: ".$Exception->getMessage();
}
try{
$stmh = $pdo->query($sql);
?>
<form name="board_form" id="board_form" method="post" action="list.php?mode=search&search=<?=$search?>">
<div class="container justify-content-center">
<div class="card mt-2 mb-4">
<div class="card-body">
<div class="d-flex mt-3 mb-2 justify-content-center">
<h5> <?=$title_message?> </h5>
</div>
<div class="d-flex mt-3 mb-1 justify-content-center align-items-center">
<div class="input-group p-1 mb-1 justify-content-center">
<button type="button" class="btn btn-dark btn-sm me-2" id="writeBtn"> <ion-icon name="pencil-outline"></ion-icon> 신규 </button>
<input type="text" name="search" id="search" value="<?=$search?>" size="30" onkeydown="JavaScript:SearchEnter();" placeholder="검색어">
<button type="button" id="searchBtn" class="btn btn-dark" > <ion-icon name="search-outline"></ion-icon> </button>
</div>
</div>
<div class="row d-flex" >
<table class="table table-hover" id="myTable">
<thead class="table-primary" >
<tr>
<th class="text-center" > 번호 </th>
<th class="text-center" > 글제목 </th>
<th class="text-center" > 작성자 </th>
<th class="text-center" > 등록일자 </th>
<th class="text-center" > 조회수 </th>
</tr>
</thead>
<tbody>
<?php
$start_num=$total_row; // 페이지당 표시되는 첫번째 글순번
while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
include '_row.php';
$subject=str_replace(" ", "&nbsp;", $row["subject"]);
$sql="select * from {$DB}.{$tablename}_ripple where parent=$num";
$stmh1 = $pdo->query($sql);
$num_ripple=$stmh1->rowCount();
?>
<tr onclick="redirectToView('<?=$num?>', '<?=$tablename?>')">
<td class="text-center" > <?= $start_num ?> </td>
<td class="text-start"> <?= $subject ?>
<?php
if($num_ripple>0)
echo '<span class="badge bg-primary "> '.$num_ripple.' </span> ';
?>
</td>
<td class="text-center" > <?= $name ?> </td>
<td class="text-center" > <?= $regist_day ?> </td>
<td class="text-center" > <?= $hit ?> </td>
</tr>
<?php
$start_num--;
}
} catch (PDOException $Exception) {
print "오류: ".$Exception->getMessage();
}
?>
</tbody>
</table>
</div>
</div> <!--card-body-->
</div> <!--card -->
</div> <!--container-->
</form>
</body>
</html>
<!-- 페이지로딩 -->
<script>
// 페이지 로딩
$(document).ready(function(){
var loader = document.getElementById('loadingOverlay');
loader.style.display = 'none';
});
</script>
<script>
var dataTable; // DataTables 인스턴스 전역 변수
var noticepageNumber; // 현재 페이지 번호 저장을 위한 전역 변수
$(document).ready(function() {
// DataTables 초기 설정
dataTable = $('#myTable').DataTable({
"paging": true,
"ordering": true,
"searching": true,
"pageLength": 50,
"lengthMenu": [25, 50, 100, 200, 500, 1000],
"language": {
"lengthMenu": "Show _MENU_ entries",
"search": "Live Search:"
},
"order": [[0, 'desc']]
});
// 페이지 번호 복원 (초기 로드 시)
var savedPageNumber = getCookie('noticepageNumber');
if (savedPageNumber) {
dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
}
// 페이지 변경 이벤트 리스너
dataTable.on('page.dt', function() {
var noticepageNumber = dataTable.page.info().page + 1;
setCookie('noticepageNumber', noticepageNumber, 10); // 쿠키에 페이지 번호 저장
});
// 페이지 길이 셀렉트 박스 변경 이벤트 처리
$('#myTable_length select').on('change', function() {
var selectedValue = $(this).val();
dataTable.page.len(selectedValue).draw(); // 페이지 길이 변경 (DataTable 파괴 및 재초기화 없이)
// 변경 후 현재 페이지 번호 복원
savedPageNumber = getCookie('noticepageNumber');
if (savedPageNumber) {
dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
}
});
});
function restorePageNumber() {
var savedPageNumber = getCookie('noticepageNumber');
if (savedPageNumber) {
dataTable.page(parseInt(savedPageNumber) - 1).draw('page');
}
}
function redirectToView(num, tablename) {
var page = noticepageNumber; // 현재 페이지 번호 (+1을 해서 1부터 시작하도록 조정)
var url = "view.php?num=" + num + "&tablename=" + tablename;
customPopup(url, '공지사항', 1200, 900);
}
$(document).ready(function(){
$("#writeBtn").click(function(){
var page = noticepageNumber; // 현재 페이지 번호 (+1을 해서 1부터 시작하도록 조정)
var tablename = '<?php echo $tablename; ?>';
var url = "write_form.php?tablename=" + tablename;
customPopup(url, '공지사항', 1300, 850);
});
});
</script>

410
notice1/view.php Normal file
View File

@@ -0,0 +1,410 @@
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/load_GoogleDrive.php'; // 세션 등 여러가지 포함됨 파일 포함
// 첫 화면 표시 문구
$title_message = '공지사항';
if(!isset($_SESSION["level"]) || $_SESSION["level"]>5) {
sleep(1);
header("Location:" . $WebSite . "login/login_form.php");
exit;
}
include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php';
?>
<title> <?=$title_message?> </title>
</head>
<body>
<?php include $_SERVER['DOCUMENT_ROOT'] . "/mymodal.php"; ?>
<?php
$num=$_REQUEST["num"] ?? '';
$tablename=$_REQUEST["tablename"] ?? '';
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();
try{
$sql = "select * from " . $DB . "." . $tablename . " where num=?";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $num, PDO::PARAM_STR);
$stmh->execute();
$row = $stmh->fetch(PDO::FETCH_ASSOC);
include '_row.php';
if($noticecheck=='y')
$noticecheck_memo='(전체공지)';
else
$noticecheck_memo='';
if ($is_html=='y'){
// $content = str_replace(" ", "&nbsp;", $content);
// $content = str_replace("\n", "<br>", $content);
$content = htmlspecialchars_decode($content);
}
// $content = str_replace("\n", "<br>", $content);
$content = str_replace("\r", "<br>", $content);
$new_hit = $hit + 1;
try{
$pdo->beginTransaction();
$sql = "update " . $DB . "." . $tablename . " set hit=? where num=?"; // 글 조회수 증가
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $new_hit, PDO::PARAM_STR);
$stmh->bindValue(2, $num, PDO::PARAM_STR);
$stmh->execute();
$pdo->commit();
} catch (PDOException $Exception) {
$pdo->rollBack();
print "오류: ".$Exception->getMessage();
}
// 초기 프로그램은 $num사용 이후 $id로 수정중임
$id=$num;
$author_id = $row["id"] ?? '';
require_once $_SERVER['DOCUMENT_ROOT'] . '/load_GoogleDriveSecond.php'; // attached, image에 대한 정보 불러오기
// print_r($saveimagename_arr);
?>
<form id="board_form" name="board_form" method="post" enctype="multipart/form-data">
<input type="hidden" id="tablename" name="tablename" value="<?=$tablename?>" >
<input type="hidden" id="id" name="id" value="<?=$id?>" >
<input type="hidden" id="num" name="num" value="<?=$num?>" >
<input type="hidden" id="item" name="item" value="<?=$item?>" >
<input type="hidden" id="mode" name="mode" value="<?=$mode?>" >
<input type="hidden" id="timekey" name="timekey" value="<?=$timekey?>" > <!-- 신규데이터 작성시 parentid key값으로 사용 -->
<input type="hidden" id="searchtext" name="searchtext" value="<?=$searchtext?>" > <!-- summernote text저장 -->
</form>
<div class="container">
<div class="card mt-2 mb-4">
<div class="card-body">
<div class="d-flex mt-3 mb-2 justify-content-center">
<h5> <?=$title_message?> </h5>
</div>
<div class="d-flex p-1 m-1 mt-2 mb-2 justify-content-left align-items-center">
<button type="button" id="closeBtn" class="btn btn-dark btn-sm me-1" > <ion-icon name="close-outline"></ion-icon> 창닫기 </button>
<?php
// 삭제 수정은 관리자와 글쓴이만 가능토록 함
if(isset($_SESSION["userid"])) {
if($user_name == $name || $_SESSION["userid"]=="admin" ||
intval($level) ==1 )
{
?>
<button type="button" class="btn btn-dark btn-sm me-1" onclick="location.href='write_form.php?tablename=<?=$tablename?>&mode=modify&num=<?=$num?>'" > <ion-icon name="color-wand-outline"></ion-icon> 수정 </button>
<button type="button" class="btn btn-dark btn-sm me-1" onclick="location.href='write_form.php?tablename=<?=$tablename?>'" > <ion-icon name="create-outline"></ion-icon> 신규 </button>
<button type="button" class="btn btn-danger btn-sm me-1" onclick="javascript:del('delete.php?tablename=<?=$tablename?>&num=<?=$num?>')" > <ion-icon name="trash-outline"></ion-icon> 삭제 </button>
<?php } ?>
</div>
<div class="card">
<div class="card-body">
<div class="row d-flex p-2 m-2 mt-1 mb-1 justify-content-center bg-secondary text-white align-items-center">
<div class="col-7 text-start fw-bold fs-6" > <?= $subject ?> </div>
<div class="col-5 text-end" > <?= $noticecheck_memo ?> |<?= $name ?> | 조회 : <?= $hit ?> | <?= $regist_day ?> </div>
</div>
<div class="row d-flex p-2 m-2 mt-1 mb-1 justify-content-left">
<?=$content ?>
</div>
</div>
</div>
<div class="row d-flex p-2 m-2 mt-1 mb-1 justify-content-left ">
<div id ="displayImage"> </div>
</div>
</div>
<div class="card" id ="displayFile" style="display:none;"> </div>
</div>
<div class="row p-1 m-1 mt-1 mb-1 justify-content-center align-items-center">
<?php
try{
$sql = "select * from {$DB}.{$tablename}_ripple where parent='$num'";
$stmh1 = $pdo->query($sql); // ripple PDOStatement 변수명을 다르게
} catch (PDOException $Exception) {
print "오류: ".$Exception->getMessage();
}
while ($row_ripple = $stmh1->fetch(PDO::FETCH_ASSOC)) {
$ripple_num = $row_ripple["num"];
$ripple_id = $row_ripple["id"];
$ripple_name = $row_ripple["name"];
$ripple_content = str_replace("\n", "", $row_ripple["content"]);
$ripple_content = str_replace(" ", "&nbsp;", $ripple_content);
$ripple_date = $row_ripple["regist_day"];
?>
<div class="card" style="width:80% ">
<div class="row justify-content-center">
<div class="card-body">
<span class="mt-1 mb-2"> ▶ &nbsp;&nbsp; <?=$ripple_content?> ✔&nbsp;&nbsp; 작성자 :
<?=$ripple_name?> | <?=$ripple_date?>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
<?php
if (isset($_SESSION["userid"])) {
if ($_SESSION["userid"] == "admin" || $_SESSION["userid"] == $ripple_id || $_SESSION["level"] === 1) {
print "<button type='button' class='btn btn-danger btn-sm' onclick='rippledelete(\"$tablename\", \"$num\", \"$ripple_num\")'> <ion-icon name='trash-outline'></ion-icon> </button>";
}
}
print '</span> </div> </div> </div>';
}
?>
</div>
<form id="ripple_form" name="ripple_form" method="post" action="insert_ripple.php">
<!-- 전달함수 설정 input hidden -->
<input type="hidden" id="id" name="num" value="<?= isset($num) ? $num : '' ?>" >
<input type="hidden" id="id" name="id" value="<?= isset($id) ? $id : '' ?>" >
<input type="hidden" id="parentid" name="parentid" value="<?= isset($parentid) ? $parentid : '' ?>" >
<input type="hidden" id="fileorimage" name="fileorimage" value="<?= isset($fileorimage) ? $fileorimage : '' ?>" >
<input type="hidden" id="item" name="item" value="<?= isset($item) ? $item : '' ?>" >
<input type="hidden" id="upfilename" name="upfilename" value="<?= isset($upfilename) ? $upfilename : '' ?>" >
<input type="hidden" id="tablename" name="tablename" value="<?= isset($tablename) ? $tablename : '' ?>" >
<input type="hidden" id="savetitle" name="savetitle" value="<?= isset($savetitle) ? $savetitle : '' ?>" >
<input type="hidden" id="pInput" name="pInput" value="<?= isset($pInput) ? $pInput : '' ?>" >
<input type="hidden" id="mode" name="mode" value="<?= isset($mode) ? $mode : '' ?>" >
<div class="row p-1 m-1 mt-1 mb-1 justify-content-center">
<div class="card" style="width:80% ">
<div class="row">
<div class="card-body">
<div class="row d-flex mt-3 mb-1 justify-content-center align-items-center">
<div class="d-flex align-items-center">
<span class="badge bg-secondary text-center fs-6 me-1" style="width:10%;"> <ion-icon name="return-down-forward-outline"></ion-icon> 댓글 </span>
<textarea rows="1" class="form-control me-1" id="ripple_content" name="ripple_content" required></textarea>
<button type="button" class="btn btn-dark btn-sm" style="width:15%;" onclick="document.getElementById('ripple_form').submit();"> <ion-icon name="save-outline"></ion-icon> 댓글 저장</button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<?php
}
} catch (PDOException $Exception) {
print "오류: ".$Exception->getMessage();
}
?>
</div>
</div>
</div>
</body>
</html>
<!-- 페이지로딩 -->
<script>
// 페이지 로딩
$(document).ready(function(){
var loader = document.getElementById('loadingOverlay');
loader.style.display = 'none';
});
</script>
<script>
$(document).ready(function(){
$('#closeBtn').click(function() {
window.close(); // 현재 창 닫기
});
$("#closeModalBtn").click(function(){
$('#myModal').modal('hide');
});
// 하단복사 버튼
$("#closeBtn1").click(function(){
$("#closeBtn").click();
});
}); // end of ready document
function del(href) {
var user_id = '<?php echo $user_id ; ?>' ;
var author_id = '<?php echo $author_id ; ?>' ;
var admin = '<?php echo $admin ; ?>' ;
if( user_id !== author_id && admin !== '1' )
{
Swal.fire({
title: '삭제불가',
text: "작성자와 관리자만 삭제가능합니다.",
icon: 'error',
confirmButtonText: '확인'
});
} else {
Swal.fire({
title: '자료 삭제',
text: "삭제는 신중! 정말 삭제하시겠습니까?",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: '삭제',
cancelButtonText: '취소'
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
url: "delete.php",
type: "post",
data: $("#board_form").serialize(),
dataType:"json",
success : function( data ){
console.log(data);
Toastify({
text: "파일 삭제완료 ",
duration: 2000,
close:true,
gravity:"top",
position: "center",
style: {
background: "linear-gradient(to right, #00b09b, #96c93d)"
},
}).showToast();
setTimeout(function(){
if (window.opener && !window.opener.closed) {
window.opener.restorePageNumber(); // 부모 창에서 페이지 번호 복원
window.opener.location.reload(); // 부모 창 새로고침
window.close();
}
}, 1000);
},
error : function( jqxhr , status , error ){
console.log( jqxhr , status , error );
}
});
}
});
}
}
function rippledelete(tablename, num, ripple_num) {
Swal.fire({
title: '댓글 삭제',
text: "정말 삭제하시겠습니까?",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: '삭제',
cancelButtonText: '취소'
}).then((result) => {
if (result.isConfirmed) {
window.location.href = `delete_ripple.php?tablename=${tablename}&num=${num}&ripple_num=${ripple_num}`;
}
});
}
</script>
<script>
$(document).ready(function(){
displayFileLoad();
displayImageLoad();
}); // end of ready document
// 기존 있는 이미지 화면에 보여주기
function displayImageLoad() {
$('#displayImage').show();
var saveimagename_arr = <?php echo json_encode($saveimagename_arr);?> ;
$("#displayImage").html('');
saveimagename_arr.forEach(function(pic, index) {
var thumbnail = pic.thumbnail || '/assets/default-thumbnail.png';
const realName = pic.realname || '다운로드 파일';
var link = pic.link || '#';
var fileId = pic.fileId || null;
if (!fileId) {
console.error("fileId가 누락되었습니다. index: " + index, pic);
return; // fileId가 없으면 해당 항목 건너뛰기
}
$("#displayImage").append(
"<div class='row mt-2 mb-1'>" +
"<div class='d-flex justify-content-center mt-1 mb-1'>" +
"<a href='#' onclick=\"popupCenter('" + link + "', 'imagePopup', 800, 600); return false;\">" +
"<img id='pic" + index + "' src='" + thumbnail + "' style='width:300px; height:auto;'>" +
"</a>" +
"</div>" +
"</div>"
);
});
}
// 기존 파일 불러오기 (Google Drive에서 가져오기)
function displayFileLoad() {
$('#displayFile').show();
var data = <?php echo json_encode($savefilename_arr); ?>;
$("#displayFile").html(''); // 기존 내용 초기화
if (Array.isArray(data) && data.length > 0) {
data.forEach(function (fileData, i) {
const realName = fileData.realname || '다운로드 파일';
const link = fileData.link || '#';
const fileId = fileData.fileId || null;
if (!fileId) {
console.error("fileId가 누락되었습니다. index: " + i, fileData);
return;
}
// 파일 정보 행 추가
$("#displayFile").append(
"<div class='row mb-3'>" +
"<div id='file" + i + "' class='col d-flex align-items-center justify-content-center'>" +
"<a href='#' onclick=\"popupCenter('" + link + "', 'filePopup', 800, 600); return false;\">" +
realName +
"</a> &nbsp; &nbsp; " +
"</div>" +
"</div>"
);
});
} else {
$("#displayFile").append(
"<div class='text-center text-muted'>No attached files</div>"
);
}
}
</script>
</body>
</html>

840
notice1/write_form.php Normal file
View File

@@ -0,0 +1,840 @@
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/load_GoogleDrive.php'; // 세션 등 여러가지 포함됨 파일 포함
// 첫 화면 표시 문구
$title_message = '공지사항';
if(!isset($_SESSION["level"]) || $_SESSION["level"]>5) {
sleep(1);
header("Location:" . $WebSite . "login/login_form.php");
exit;
}
include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php';
?>
<title> <?=$title_message?> </title>
</head>
<body>
<?php include $_SERVER['DOCUMENT_ROOT'] . "/mymodal.php"; ?>
<?php
isset($_REQUEST["id"]) ? $id=$_REQUEST["id"] : $id='';
isset($_REQUEST["num"]) ? $num=$_REQUEST["num"] : $num='';
isset($_REQUEST["fileorimage"]) ? $fileorimage=$_REQUEST["fileorimage"] : $fileorimage=''; // file or image
isset($_REQUEST["item"]) ? $item=$_REQUEST["item"] : $item='';
isset($_REQUEST["upfilename"]) ? $upfilename=$_REQUEST["upfilename"] : $upfilename='';
isset($_REQUEST["tablename"]) ? $tablename=$_REQUEST["tablename"] : $tablename='notice';
isset($_REQUEST["mode"]) ? $mode=$_REQUEST["mode"] : $mode='';
$is_html = $_REQUEST["is_html"] ?? "";
$noticecheck = $_REQUEST["noticecheck"] ?? "";
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();
if ($mode=="modify"){
try{
$sql = "select * from " . $DB . "." . $tablename . " where num = ? ";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1,$num,PDO::PARAM_STR);
$stmh->execute();
$count = $stmh->rowCount();
if($count<1){
print "검색결과가 없습니다.<br>";
}else{
$row = $stmh->fetch(PDO::FETCH_ASSOC);
include '_row.php';
}
}catch (PDOException $Exception) {
print "오류: ".$Exception->getMessage();
}
}
else
{
$content = null;
}
// 초기 프로그램은 $num사용 이후 $id로 수정중임
$id=$num;
require_once $_SERVER['DOCUMENT_ROOT'] . '/load_GoogleDriveSecond.php'; // attached, image에 대한 정보 불러오기
?>
<form id="board_form" name="board_form" method="post" enctype="multipart/form-data">
<!-- 전달함수 설정 input hidden -->
<input type="hidden" id="tablename" name="tablename" value="<?=$tablename?>" >
<input type="hidden" id="id" name="id" value="<?=$id?>" >
<input type="hidden" id="num" name="num" value="<?=$num?>" >
<input type="hidden" id="item" name="item" value="<?=$item?>" >
<input type="hidden" id="mode" name="mode" value="<?=$mode?>" >
<input type="hidden" id="timekey" name="timekey" value="<?=$timekey?>" > <!-- 신규데이터 작성시 parentid key값으로 사용 -->
<input type="hidden" id="searchtext" name="searchtext" value="<?=$searchtext?>" > <!-- summernote text저장 -->
<div class="container">
<div class="d-flex mt-3 mb-1 justify-content-center align-items-center">
<h5> <?=$title_message?> </h5>
</div>
<div class="d-flex mt-2 mb-1 justify-content-center align-items-center">
<div class="card mt-2" style="width:60%;">
<div class="card-body">
<div class="d-flex mt-2 mb-1 justify-content-center align-items-center">
<div class="row">
<div class="col-3-sm">
<div class="d-flex justify-content-center align-items-center">
작성자 : &nbsp; <?=$_SESSION["name"]?> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="checkbox" name="is_html" value="y" <?php if($is_html=='y') print 'checked'; ?> >&nbsp; HTML 쓰기 &nbsp;
<input type="checkbox" name="noticecheck" value="y" <?php if($noticecheck=='y') print 'checked'; ?> > &nbsp; 전체공지
</div>
</div>
<div class="col-5-sm">
<div class="d-flex mt-2 justify-content-center align-items-center">
제목 &nbsp;
<input id="subject" name="subject" type="text" required autocomplete="off" class="form-control text-start" style="width:500px;" <?php if($mode=="modify"){ ?> value="<?=$subject?>" <?php }?>>&nbsp;
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="d-flex mt-1 mb-1 justify-content-start align-items-center">
<button class="btn btn-dark btn-sm me-1" onclick="self.close();" > &times; 닫기 </button>
<button type="button" class="btn btn-dark btn-sm" id="saveBtn" > <i class="bi bi-floppy-fill"></i> 저장 </button>
</div>
<div class="d-flex justify-content-start align-items-center">
<textarea id="summernote" name="content" rows="20" required><?=$content?></textarea>
</div>
<div class="d-flex mt-1 mb-1 justify-content-center">
<label for="upfileimage" class="input-group-text btn btn-outline-dark btn-sm "> 사진 첨부 </label>
<input id="upfileimage" name="upfileimage[]" type="file" onchange="this.value" multiple accept=".gif, .jpg, .png" style="display:none">
</div>
<div id ="displayImage" style="display:none;"> </div>
<div class="d-flex mt-3 mb-1 justify-content-center">
<label for="upfile" class="input-group-text btn btn-outline-primary btn-sm"> 파일(10M 이하) pdf파일 첨부 </label>
<input id="upfile" name="upfile[]" type="file" onchange="this.value" multiple style="display:none" >
</div>
<div id ="displayFile" style="display:none;"> </div>
</div>
</form>
</body>
</html>
<!-- 페이지로딩 -->
<script>
// 페이지 로딩
$(document).ready(function(){
var loader = document.getElementById('loadingOverlay');
loader.style.display = 'none';
});
</script>
<script>
var ajaxRequest_notice = null;
$(document).ready(function(){
$('#summernote').summernote({
placeholder: '내용 작성',
// maximumImageFileSize: 500*1024, // 500 KB
maximumImageFileSize: 1920*5000,
tabsize: 2,
height: 450,
width: 1200,
toolbar: [
['style', ['style']],
['font', ['bold', 'underline', 'clear']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['table', ['table']],
['insert', ['link', 'picture', 'video']],
['view', ['fullscreen', 'codeview', 'help']]
],
callbacks: {
onImageUpload: function(files) {
if (files.length > 0) {
var file = files[0];
resizeImage(file, function(resizedImage) {
// resizedImage는 처리된 이미지의 데이터 URL입니다.
$('#summernote').summernote('insertImage', resizedImage);
});
}
}
}
});
function resizeImage(file, callback) {
var reader = new FileReader();
reader.onloadend = function(e) {
var tempImg = new Image();
tempImg.src = reader.result;
tempImg.onload = function() {
// 여기서 원하는 이미지 크기로 설정
var MAX_WIDTH = 800;
var MAX_HEIGHT = 500;
var tempW = tempImg.width;
var tempH = tempImg.height;
if (tempW > tempH) {
if (tempW > MAX_WIDTH) {
tempH *= MAX_WIDTH / tempW;
tempW = MAX_WIDTH;
}
} else {
if (tempH > MAX_HEIGHT) {
tempW *= MAX_HEIGHT / tempH;
tempH = MAX_HEIGHT;
}
}
var canvas = document.createElement('canvas');
canvas.width = tempW;
canvas.height = tempH;
var ctx = canvas.getContext("2d");
ctx.drawImage(tempImg, 0, 0, tempW, tempH);
var dataURL = canvas.toDataURL("image/jpeg");
callback(dataURL);
};
};
reader.readAsDataURL(file);
}
$("#closeModalBtn").click(function(){
$('#myModal').modal('hide');
});
// 하단복사 버튼
$("#closeBtn1").click(function(){
$("#closeBtn").click();
})
$("#closeBtn").click(function(){ // 저장하고 창닫기
opener.location.reload();
self.close();
});
$("#saveBtn").click(function(){
Fninsert();
});
// 자료의 삽입/수정하는 모듈
function Fninsert() {
console.log($("#mode").val());
// Summernote 초기화 후
let content = $('#summernote').summernote('code'); // 에디터의 내용을 HTML 형태로 가져옵니다.
// HTML 문자열을 DOM 요소로 변환
let tempDiv = document.createElement('div');
tempDiv.innerHTML = content;
// 이제 tempDiv 내부에서 원하는 태그를 선택할 수 있습니다.
let elements = tempDiv.querySelectorAll('p, b');
let extractedTexts = [];
elements.forEach(element => {
extractedTexts.push(element.textContent);
});
console.log(extractedTexts.join(','));
var extractedText = extractedTexts.join(',');
console.log('extractedTexts');
console.log(extractedTexts);
$("#searchtext").val(extractedText);
var form = $('#board_form')[0];
var data = new FormData(form);
// 폼 데이터를 콘솔에 출력하여 확인합니다.
// for (var pair of data.entries()) {
// console.log(pair[0] + ', ' + pair[1]);
// }
// console.log(data);
showMsgModal(2); // 파일저장중
if (ajaxRequest_notice !== null) {
ajaxRequest_notice.abort();
}
ajaxRequest_notice = $.ajax({
enctype: 'multipart/form-data', // file을 서버에 전송하려면 이렇게 해야 함 주의
processData: false,
contentType: false,
cache: false,
timeout: 600000,
url: "insert.php",
type: "post",
data: data,
dataType:"json",
success : function(data){
console.log(data);
setTimeout(function() {
Toastify({
text: "파일 저장완료 ",
duration: 2000,
close:true,
gravity:"top",
position: "center",
style: {
background: "linear-gradient(to right, #00b09b, #96c93d)"
},
}).showToast();
setTimeout(function(){
if (window.opener && !window.opener.closed) {
opener.location.reload();
}
}, 1000);
var num = data["num"];
var tablename = data["tablename"];
setTimeout(function(){
hideMsgModal();
location.href='view.php?num=' + num + "&tablename=" + tablename ;
}, 1000);
}, 1000);
},
error : function( jqxhr , status , error ){
console.log( jqxhr , status , error );
}
});
}
}); // end of ready document
function deleteLastchar(str)
// 마지막 문자 제거하는 함수
{
return str = str.substr(0, str.length - 1);
}
</script>
<script>
$(document).ready(function () {
displayFileLoad(); // 기존파일 업로드 보이기
displayImageLoad(); // 기존이미지 업로드 보이기
// 첨부파일 업로드 처리
$("#upfile").change(function (e) {
if (this.files.length === 0) {
// 파일이 선택되지 않았을 때
console.warn("파일이 선택되지 않았습니다.");
return;
}
const form = $('#board_form')[0];
const data = new FormData(form);
// 추가 데이터 설정
data.append("tablename", $("#tablename").val() );
data.append("item", "attached");
data.append("upfilename", "upfile"); // upfile 파일 name
data.append("folderPath", "경동기업/uploads");
data.append("DBtable", "picuploads");
showMsgModal(2); // 파일저장중
// AJAX 요청 (Google Drive API)
$.ajax({
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
timeout: 600000,
url: "/filedrive/fileprocess.php",
type: "POST",
data: data,
success: function (response) {
console.log("응답 데이터:", response);
let successCount = 0;
let errorCount = 0;
let errorMessages = [];
response.forEach((item) => {
if (item.status === "success") {
successCount++;
} else if (item.status === "error") {
errorCount++;
errorMessages.push(`파일: ${item.file}, 메시지: ${item.message}`);
}
});
if (successCount > 0) {
Toastify({
text: `${successCount}개의 파일이 성공적으로 업로드되었습니다.`,
duration: 2000,
close: true,
gravity: "top",
position: "center",
backgroundColor: "#4fbe87",
}).showToast();
}
if (errorCount > 0) {
Toastify({
text: `오류 발생: ${errorCount}개의 파일 업로드 실패\n상세 오류: ${errorMessages.join("\n")}`,
duration: 5000,
close: true,
gravity: "top",
position: "center",
backgroundColor: "#f44336",
}).showToast();
}
setTimeout(function () {
displayFile();
hideMsgModal();
}, 1000);
},
error: function (jqxhr, status, error) {
console.error("업로드 실패:", jqxhr, status, error);
},
});
});
// 첨부 이미지 업로드 처리
$("#upfileimage").change(function (e) {
if (this.files.length === 0) {
// 파일이 선택되지 않았을 때
console.warn("파일이 선택되지 않았습니다.");
return;
}
const form = $('#board_form')[0];
const data = new FormData(form);
// 추가 데이터 설정
data.append("tablename", $("#tablename").val() );
data.append("item", "image");
data.append("upfilename", "upfileimage"); // upfile 파일 name
data.append("folderPath", "경동기업/uploads");
data.append("DBtable", "picuploads");
showMsgModal(1); // 이미지저장중
// AJAX 요청 (Google Drive API)
$.ajax({
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
timeout: 600000,
url: "/filedrive/fileprocess.php",
type: "POST",
data: data,
success: function (response) {
console.log("응답 데이터:", response);
let successCount = 0;
let errorCount = 0;
let errorMessages = [];
response.forEach((item) => {
if (item.status === "success") {
successCount++;
} else if (item.status === "error") {
errorCount++;
errorMessages.push(`파일: ${item.file}, 메시지: ${item.message}`);
}
});
if (successCount > 0) {
Toastify({
text: `${successCount}개의 파일이 성공적으로 업로드되었습니다.`,
duration: 2000,
close: true,
gravity: "top",
position: "center",
backgroundColor: "#4fbe87",
}).showToast();
}
if (errorCount > 0) {
Toastify({
text: `오류 발생: ${errorCount}개의 파일 업로드 실패\n상세 오류: ${errorMessages.join("\n")}`,
duration: 5000,
close: true,
gravity: "top",
position: "center",
backgroundColor: "#f44336",
}).showToast();
}
setTimeout(function () {
displayImage();
hideMsgModal();
}, 1000);
},
error: function (jqxhr, status, error) {
console.error("업로드 실패:", jqxhr, status, error);
},
});
});
});
// 화면에서 저장한 첨부된 파일 불러오기
function displayFile() {
$('#displayFile').show();
const params = $("#timekey").val() ? $("#timekey").val() : $("#num").val();
if (!params) {
console.error("ID 값이 없습니다. 파일을 불러올 수 없습니다.");
alert("ID 값이 유효하지 않습니다. 다시 시도해주세요.");
return;
}
console.log("요청 ID:", params); // 요청 전 ID 확인
$.ajax({
url: '/filedrive/fileprocess.php',
type: 'GET',
data: {
num: params,
tablename: $("#tablename").val(),
item: 'attached',
folderPath: '경동기업/uploads',
},
dataType: 'json',
}).done(function (data) {
console.log("파일 데이터:", data);
$("#displayFile").html(''); // 기존 내용 초기화
if (Array.isArray(data) && data.length > 0) {
data.forEach(function (fileData, index) {
const realName = fileData.realname || '다운로드 파일';
const link = fileData.link || '#';
const fileId = fileData.fileId || null;
if (!fileId) {
console.error("fileId가 누락되었습니다. index: " + index, fileData);
$("#displayFile").append(
"<div class='text-danger'>파일 ID가 누락되었습니다.</div>"
);
return;
}
$("#displayFile").append(
"<div class='row mt-1 mb-2'>" +
"<div class='d-flex align-items-center justify-content-center'>" +
"<span id='file" + index + "'>" +
"<a href='#' onclick=\"popupCenter('" + link + "', 'filePopup', 800, 600); return false;\">" + realName + "</a>" +
"</span> &nbsp;&nbsp;" +
"<button type='button' class='btn btn-danger btn-sm' id='delFile" + index + "' onclick=\"delFileFn('" + index + "', '" + fileId + "')\">" +
"<i class='bi bi-trash'></i>" +
"</button>" +
"</div>" +
"</div>"
);
});
} else {
$("#displayFile").append(
"<div class='text-center text-muted'>No files</div>"
);
}
}).fail(function (error) {
console.error("파일 불러오기 오류:", error);
Swal.fire({
title: "파일 불러오기 실패",
text: "파일을 불러오는 중 문제가 발생했습니다.",
icon: "error",
confirmButtonText: "확인",
});
});
}
// 기존 파일 불러오기 (Google Drive에서 가져오기)
function displayFileLoad() {
$('#displayFile').show();
var data = <?php echo json_encode($savefilename_arr); ?>;
$("#displayFile").html(''); // 기존 내용 초기화
if (Array.isArray(data) && data.length > 0) {
data.forEach(function (fileData, i) {
const realName = fileData.realname || '다운로드 파일';
const link = fileData.link || '#';
const fileId = fileData.fileId || null;
if (!fileId) {
console.error("fileId가 누락되었습니다. index: " + i, fileData);
return;
}
$("#displayFile").append(
"<div class='row mb-3'>" +
"<div class='d-flex mb-3 align-items-center justify-content-center'>" +
"<span id='file" + i + "'>" +
"<a href='#' onclick=\"popupCenter('" + link + "', 'filePopup', 800, 600); return false;\">" + realName + "</a>" +
"</span> &nbsp;&nbsp;" +
"<button type='button' class='btn btn-danger btn-sm' id='delFile" + i + "' onclick=\"delFileFn('" + i + "', '" + fileId + "')\">" +
"<i class='bi bi-trash'></i>" +
"</button>" +
"</div>" +
"</div>"
);
});
} else {
$("#displayFile").append(
"<div class='text-center text-muted'>No files</div>"
);
}
}
// 파일 삭제 처리 함수
function delFileFn(divID, fileId) {
Swal.fire({
title: "파일 삭제 확인",
text: "정말 삭제하시겠습니까?",
icon: "warning",
showCancelButton: true,
confirmButtonText: "삭제",
cancelButtonText: "취소",
reverseButtons: true,
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
url: '/filedrive/fileprocess.php',
type: 'DELETE',
data: JSON.stringify({
fileId: fileId,
tablename: $("#tablename").val(),
item: "attached",
folderPath: "경동기업/uploads",
DBtable: "picuploads",
}),
contentType: "application/json",
dataType: 'json',
}).done(function (response) {
if (response.status === 'success') {
console.log("삭제 완료:", response);
$("#file" + divID).remove();
$("#delFile" + divID).remove();
Swal.fire({
title: "삭제 완료",
text: "파일이 성공적으로 삭제되었습니다.",
icon: "success",
confirmButtonText: "확인",
});
} else {
console.log(response.message);
}
}).fail(function (error) {
console.error("삭제 중 오류:", error);
Swal.fire({
title: "삭제 실패",
text: "파일 삭제 중 문제가 발생했습니다.",
icon: "error",
confirmButtonText: "확인",
});
});
}
});
}
// 첨부된 이미지 불러오기
function displayImage() {
$('#displayImage').show();
const params = $("#timekey").val() ? $("#timekey").val() : $("#num").val();
if (!params) {
console.error("ID 값이 없습니다. 파일을 불러올 수 없습니다.");
alert("ID 값이 유효하지 않습니다. 다시 시도해주세요.");
return;
}
console.log("요청 ID:", params); // 요청 전 ID 확인
$.ajax({
url: '/filedrive/fileprocess.php',
type: 'GET',
data: {
num: params,
tablename: $("#tablename").val(),
item: 'image',
folderPath: '경동기업/uploads',
},
dataType: 'json',
}).done(function (data) {
console.log("파일 데이터:", data);
$("#displayImage").html(''); // 기존 내용 초기화
if (Array.isArray(data) && data.length > 0) {
data.forEach(function (fileData, index) {
const realName = fileData.realname || '다운로드 파일';
const thumbnail = fileData.thumbnail || '/assets/default-thumbnail.png';
const link = fileData.link || '#';
const fileId = fileData.fileId || null;
if (!fileId) {
console.error("fileId가 누락되었습니다. index: " + index, fileData);
$("#displayImage").append(
"<div class='text-danger'>파일 ID가 누락되었습니다.</div>"
);
return;
}
$("#displayImage").append(
"<div class='row mb-3'>" +
"<div class='col d-flex align-items-center justify-content-center'>" +
"<a href='#' onclick=\"popupCenter('" + link + "', 'imagePopup', 800, 600); return false;\">" +
"<img id='image" + index + "' src='" + thumbnail + "' style='width:150px; height:auto;'>" +
"</a> &nbsp;&nbsp;" +
"<button type='button' class='btn btn-danger btn-sm' id='delImage" + index + "' onclick=\"delImageFn('" + index + "', '" + fileId + "')\">" +
"<i class='bi bi-trash'></i>" +
"</button>" +
"</div>" +
"</div>"
);
});
} else {
$("#displayImage").append(
"<div class='text-center text-muted'>No files</div>"
);
}
}).fail(function (error) {
console.error("파일 불러오기 오류:", error);
Swal.fire({
title: "파일 불러오기 실패",
text: "파일을 불러오는 중 문제가 발생했습니다.",
icon: "error",
confirmButtonText: "확인",
});
});
}
// 기존 이미지 불러오기 (Google Drive에서 가져오기)
function displayImageLoad() {
$('#displayImage').show();
var data = <?php echo json_encode($saveimagename_arr); ?>;
$("#displayImage").html(''); // 기존 내용 초기화
if (Array.isArray(data) && data.length > 0) {
data.forEach(function (fileData, i) {
const realName = fileData.realname || '다운로드 파일';
const thumbnail = fileData.thumbnail || '/assets/default-thumbnail.png';
const link = fileData.link || '#';
const fileId = fileData.fileId || null;
if (!fileId) {
console.error("fileId가 누락되었습니다. index: " + i, fileData);
return;
}
$("#displayImage").append(
"<div class='row mb-3'>" +
"<div class='col d-flex align-items-center justify-content-center'>" +
"<a href='#' onclick=\"popupCenter('" + link + "', 'imagePopup', 800, 600); return false;\">" +
"<img id='image" + i + "' src='" + thumbnail + "' style='width:150px; height:auto;'>" +
"</a> &nbsp;&nbsp;" +
"<button type='button' class='btn btn-danger btn-sm' id='delImage" + i + "' onclick=\"delImageFn('" + i + "', '" + fileId + "')\">" +
"<i class='bi bi-trash'></i>" +
"</button>" +
"</div>" +
"</div>"
);
});
} else {
$("#displayImage").append(
"<div class='text-center text-muted'>No files</div>"
);
}
}
// 이미지 삭제 처리 함수
function delImageFn(divID, fileId) {
Swal.fire({
title: "이미지 삭제 확인",
text: "정말 삭제하시겠습니까?",
icon: "warning",
showCancelButton: true,
confirmButtonText: "삭제",
cancelButtonText: "취소",
reverseButtons: true,
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
url: '/filedrive/fileprocess.php',
type: 'DELETE',
data: JSON.stringify({
fileId: fileId,
tablename: $("#tablename").val(),
item: "image",
folderPath: "경동기업/uploads",
DBtable: "picuploads",
}),
contentType: "application/json",
dataType: 'json',
}).done(function (response) {
if (response.status === 'success') {
console.log("삭제 완료:", response);
$("#image" + divID).remove();
$("#delImage" + divID).remove();
Swal.fire({
title: "삭제 완료",
text: "파일이 성공적으로 삭제되었습니다.",
icon: "success",
confirmButtonText: "확인",
});
} else {
console.log(response.message);
}
}).fail(function (error) {
console.error("삭제 중 오류:", error);
Swal.fire({
title: "삭제 실패",
text: "파일 삭제 중 문제가 발생했습니다.",
icon: "error",
confirmButtonText: "확인",
});
});
}
});
}
</script>
</body>
</html>