소스 파일 : /navigation/naviUpdate_JSON.php (2022-08-27)     소스 설명 : ㅊㅊ
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
<?php // (2022.9.9, 차재복, Cha Jae Bok, http://www.ktword.co.kr)

# 세션 설정
	// 세션 스타트 (매 웹페이지 마다 필요)
	session_start();

	// 세션 변수에 따른 사용자 타입 설정 ('일반사용자' or '테스트편집자' or '정식편집자' or '종합관리자')
	$_SESSION['user_type'] = ( empty($_SESSION['user_name']) ? '일반사용자' : $_SESSION['user_name'] );

# 편집 권한 확인
	if ($_SESSION['user_type']!='종합관리자') {
		echo json_encode(array('err_msg'=>'편집권한없음!'), JSON_UNESCAPED_UNICODE);
		exit;
	}
	// ('일반사용자' or '테스트편집자' or '정식편집자' or '종합관리자')

# db 접속 (dbi)
	include_once "../base_utils/db_conn.php";

# 매개변수 처리
    // json 포멧 수신 받아들임
    $json = file_get_contents('php://input');
    // json 포멧 => array 포멧 변환
    $jsonArr = json_decode($json, true);
        // 전달매개변수 : type, choice, id (parent), seq_matched {seq:id/no}, 

# choice별 선택 처리
    // 특정 부모 노드 산하의 용어해설 항목 리스트 순서 업데이트
    if($jsonArr['type'] == 'word' and $jsonArr['choice'] == 'wordOrderInNode') {

        if(count($jsonArr['seq_matched'])>0) { 
            $setStr = "list_ord=";
            $setStr .= "(case ";
            foreach($jsonArr['seq_matched'] as $key=>$value) {
                $setStr .=  " when no={$value} then $key";
            }
            $setStr .= " end)"; 
        }

        $query = "update book_idx set $setStr where tree_id={$jsonArr['id']}";
	    $result = mysqli_query($dbi,$query);
		    if (mysqli_errno($dbi)) { $err_msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
    
    	if (!$result or !empty($err_msg)) $err_msg .= ' 에러 발생 ';
        else $result_msg = '업데이트 개수 : '.mysqli_affected_rows($dbi);

        $return = array('query'=>$query, 'result'=>$result_msg, 'err_msg'=>$err_msg); 

  	    // 송출
    	echo json_encode($return, JSON_UNESCAPED_UNICODE);

    // 특정 부모 노드 산하의 소스 파일 리스트 순서 업데이트
    } else if ($jsonArr['type'] == 'source' and $jsonArr['choice'] == 'sourceOrderingInNode') {

            $setStr = "seq=";
            $setStr .= " (case ";
            foreach($jsonArr['seq_matched'] as $key=>$value) {
                $setStr .=  " when id=? then ?";
            }
            $setStr .= " end)"; 


        $query = "update src_files_v3 set {$setStr} where parent=?";
//        $query = "update src_files_v3 set seq= (case when id=? then ? end) where parent=?";
        $stmt = mysqli_prepare($dbi, $query);
		    if (mysqli_errno($dbi)) { $err_msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }

            $varStr = array();
            foreach($jsonArr['seq_matched'] as $key=>$value) {
                $typeStr .= "ii";
                $varStr[] = (int) $value;
                $varStr[] = $key;
            }
            $typeStr .= "i"; 
            $varStr[] = (int) $jsonArr['id'];

        mysqli_stmt_bind_param($stmt, $typeStr, ...$varStr);
		    if (mysqli_errno($dbi)) { $err_msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }

        mysqli_stmt_execute($stmt);
		    if (mysqli_errno($dbi)) { $err_msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }

        $return = array('query'=>$query,'typeStr'=>$typeStr,'varStr'=>$varStr, 'err_msg'=>$err_msg); 

  	    // 송출
    	echo json_encode($return, JSON_UNESCAPED_UNICODE);

    // 다수의 용어해설 항목을, 부모 id 내 한꺼번에 자식으로 분류 지정 (copyWord)
    } else if ($jsonArr['choice'] == 'copyWord' and !empty($jsonArr['leftNoList']) 
                and !empty($jsonArr['rightId']) and !empty($jsonArr['targetType'])) {

        // 해킹 방어
        if(strlen($jsonArr['leftNoList'])>30) exit('너무 많은 문자열');
   		if ( !empty($jsonArr['rightId']) and !is_numeric($jsonArr['rightId']) or $jsonArr['rightId']<0 ) exit('잘못된 id'); 

        // prepare_sql 함수, treeNodeCheck 함수 준비
        include_once "naviUpdate_utils.php";

        // prepare_sql를 위한, 소스 no들의 분리 처리
        $list = explode(';',$jsonArr['leftNoList']);
        if(empty($list[0])) return;
        foreach($list as $val) {
            $in_str_i .= "?,";
            $in_str_r .= explode(',',$val)[1].",";
            $id_no[] = array(explode(',',$val)[0],explode(',',$val)[1]);
            $types .= 'i';
            $parms_arr[] = explode(',',$val)[1];
        }
        $in_str_i = substr($in_str_i,0,-1);
        $in_str_r = substr($in_str_r,0,-1);
        $types .= 'i';
        $parms_arr[] = $jsonArr['rightId'];

        // prepare_sql 실행
        $query = "select tree_id,no,titlename from book_idx where no in ({$in_str_i}) or tree_id=? order by tree_id,list_ord";
        $resultArr = prepare_sql($dbi, $query, $types, $parms_arr);
        while ($row = mysqli_fetch_assoc($resultArr['result'])) {
            $getList[$row['tree_id']][$row['no']] = $row['titlename'];
        }
        
        // 결과 셋 분석 처리 후 insert value 만들기
        $parent = $jsonArr['rightId'];
        $i = count($getList[$parent]);
        foreach($id_no as $val) {
            $i += 1;
            if($getList[$parent][$val[1]]) 
                exit('중복 있음');
            if($getList[$val['0']][$val['1']]) 
                $insertList .= "($parent,{$val['1']},'{$getList[$val[0]][$val[1]]}',$i),"; 
                                // (tree_id,no,titlename,list_ord)
        }
        $insertList = substr($insertList,0,-1);
        $query = "insert into book_idx
                    (tree_id,no,titlename,list_ord) values
                    {$insertList}";
        mysqli_query($dbi,$query);
		    if (mysqli_errno($dbi)) { $err_msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }

        // 해당 분류에 속한 용어들 갯수 update
        treeNodeCheck($parent, $dbi, $send=false);

        // 부모 노드의 path2node 추출
        $arr = getNodeDetail($parent,$dbi);
        $path2node = $arr['path2node'];
/*
        $query = "select path2node_v2 from gubun_tree_v2 where id=$parent limit 1";
        $result = mysqli_query($dbi,$query);
        $matched = mysqli_fetch_assoc($result);
        $path2node = $matched[path2node_v2];
*/
  	    // 송출
        $return = array('path2node'=>$path2node, 'err_msg'=>$err_msg);
    	echo json_encode($return, JSON_UNESCAPED_UNICODE);

    } else if ($jsonArr['choice'] == 'moveNode' and !empty($jsonArr['leftId']) and !empty($jsonArr['rightId']) 
                    and !empty($jsonArr['targetType'])) {
//         $jsonArr['choice'].', '.$jsonArr['leftId'].', '.$jsonArr['rightId'].', '.$jsonArr['targetType'];

        // 해킹 방어
   		if (!empty($jsonArr['leftId']) and !is_numeric($jsonArr['leftId']) or $jsonArr['leftId']<0) 
            exit('잘못된 left id');
   		if (!empty($jsonArr['rightId']) and !is_numeric($jsonArr['rightId']) or $jsonArr['rightId']<0) 
            exit('잘못된 right id');

        // prepare_sql 함수, treeNodeCheck 함수, getParentDetail() 함수 준비
        include_once "naviUpdate_utils.php";

        // 소스쪽 이동 노드를 발췌하면, 나머지 노드 seq들을 1씩 감할 필요 있음
    	$query = "update gubun_tree_v2 a 
                         left join (select parent,sub_seq from gubun_tree_v2 where id=?) b 
                         on a.parent=b.parent 
                         set a.sub_seq=(a.sub_seq-1) 
                         where a.sub_seq > b.sub_seq";
        $types = "i";
        $parms_arr = array($jsonArr['leftId']);
        $resultArr = prepare_sql($dbi, $query, $types, $parms_arr);
		    if (mysqli_stmt_errno($resultArr['stmt'])) 
                $err_msg .=  mysqli_stmt_errno($resultArr['stmt'])." : ".mysqli_stmt_error($resultArr['stmt'])."\n";

		// 타깃 노드의 parent,seq,nodeCount를 알아냄
        $arr = getNodeDetail($jsonArr['rightId'],$dbi);
        list($parent,$seq,$nodeCount) = array($arr['parent'],$arr['seq'],$arr['nodeCount']);

        if($jsonArr['targetType']=='afterTarget') {
            // 타킷 노드 이후 seq들을 1씩 증가시킴
 	    	$query = "update gubun_tree_v2 set sub_seq=(sub_seq+1) where parent=$parent and sub_seq>$seq";
            mysqli_query($dbi,$query);
		        if (mysqli_errno($dbi)) { $err_msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }

            // 소스 노드를 타킷 노드에 맞춰, parent,seq 수정(이동)
	    	$query = "update gubun_tree_v2 set parent=$parent,sub_seq=($seq+1) where id=?";
            $types = "i";
            $parms_arr = array($jsonArr['leftId']);
            $resultArr = prepare_sql($dbi, $query, $types, $parms_arr);
		        if (mysqli_stmt_errno($resultArr['stmt'])) 
                    $err_msg .= mysqli_stmt_errno($resultArr['stmt'])." : ".mysqli_stmt_error($resultArr['stmt'])."\n";

            // 타깃 노드 부모의 child 업데이트
            treeNodeCheck($parent, $dbi, $send=false);
        } else if($jsonArr['targetType']=='childTarget') {
            // 소스 노드를 타킷 자식 노드 끝에 맞춰, parent,seq 수정(이동)
	    	$query = "update gubun_tree_v2 set parent=?,sub_seq=($nodeCount+1) where id=?";
            $types = "ii";
            $parms_arr = array($jsonArr['rightId'],$jsonArr['leftId']);
            $resultArr = prepare_sql($dbi, $query, $types, $parms_arr);
		        if (mysqli_stmt_errno($resultArr['stmt'])) 
                    $err_msg .= mysqli_stmt_errno($resultArr['stmt'])." : ".mysqli_stmt_error($resultArr['stmt'])."\n";

            // 타깃 노드 부모의 child 업데이트
            treeNodeCheck($jsonArr['rightId'], $dbi, $send=false);
        }

		// 이동된 노드 자신 및 그 산하 자식들 모두에서, path2node, depth 업데이트
        $query = "select id from gubun_tree_v2 
                        where concat(',',path2node_v2,',') like concat('%',?,'%')";
        $types = "s";
        $parms_arr = array($jsonArr['leftId']);
        $resultArr = prepare_sql($dbi, $query, $types, $parms_arr);
        while($row = mysqli_fetch_assoc($resultArr['result'])) {
            $idList[] = $row['id'];
        }
        treeNodeCheck($idList, $dbi, $send=false);

        // 이동된 노드의 path2node 추출
        $arr = getNodeDetail($jsonArr['leftId'],$dbi);
        $path2node = $arr['path2node'];

        // 송출
        $return = array('path2node'=>$path2node, 'err_msg'=>$err_msg);
    	echo json_encode($return, JSON_UNESCAPED_UNICODE);

    } else if ($jsonArr['choice'] == 'etc...') {

    }

?>


Copyrightⓒ written by 차재복 (Cha Jae Bok)
"본 웹사이트 내 모든 저작물은 원출처를 밝히는 한 자유롭게 사용(상업화포함) 가능합니다"