소스 파일 : /edit/update.php (2020-09-30)     소스 설명 : (해설편집) 업데이트 전용
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
<?php // (2022.10.21, 차재복, 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']!='종합관리자')	exit ('편집 권한 없음!!!');
	// ('일반사용자' or '테스트편집자' or '정식편집자' or '종합관리자')

# db 접속
	include "../base_utils/db_conn.php";

# 전달변수
	$no = $_POST['no'];
		if ( isset($_REQUEST[no]) and !empty($no) and !is_numeric($no) or $no<0 ) exit; // 해킹방지 (수치>0)
	$in_no = $_POST['in_no'];
		if ( isset($_REQUEST[in_no]) and !empty($in_no) and !is_numeric($in_no) or $in_no<0 ) exit; // 해킹방지 (수치>0)

	$edit_str = $_POST['edit_str'];
	$pure_str = $_POST['pure_str'];

	$type = $_POST['type'];
		// preview : (신) 편집 확인, title_update : 타이틀 업데이트, old_update : (구) 편집, update : 실제 업데이트,
		// one_upload : 1개 이미지 파일 업로드, multi_upload : 다수개 이미지 파일 업로드
		// math_edit : mathjax 업데이트

	$yako = $_POST['yako'];
	$english = $_POST['english'];
	$korean = $_POST['korean'];
	$extra = $_POST['extra'];
	$sujung = $_POST['edit_date'];
		if (!empty($sujung) and !is_numeric($sujung) and ($sujung < 0 or $sujung > 100)) 
			exit ("({$sujung}) 날짜 범위 벗어남!!!"); // 해킹방지


# 공통 함수 
	include_once "../base_utils/common_utils.php";	// pair_delimiter(), synopsis_extract()
	include_once "../search/srch_utils.php";		// srch_bunryu ($no,$dbi)


# type별 처리 #

// 서버 text 결합 preview
if ($type == 'preview') {

	include_once '../reform/file_transform_v2.php';
	$abbr = string_transform($pure_str, $dbi, $no);

    // http 헤더 (json 포멧)
    header('content-type: application/json; charset=utf-8');

	// 메세지들을 json 포멧화시켜 결과 송출
	$return = array('abbr'=>$abbr);
    echo json_encode($return,JSON_UNESCAPED_UNICODE);

/*
	include_once "../view/view_body_text.php";
	body_text ($no, $abbr, $imgfilename, $dbi);
*/


// 서버 업데이트전 preview
} else if ($type == 'before_update') {
	// 필요변수 :  $type, $no, $pure_str, $dbi

	include_once '../reform/file_transform_v2.php';
	$abbr = string_transform($pure_str, $dbi, $no);
	$trans_abbr = $abbr;	// 점검용

	include_once "../view/view_body_text.php";
	$abbr = body_text_return ($no, $abbr, '', $dbi);

    // http 헤더 (json 포멧)
    header('content-type: application/json; charset=utf-8');

	// 메세지들을 json 포멧화시켜 결과 송출
	$return = array('abbr'=>$abbr,'trans_abbr'=>$trans_abbr);
    echo json_encode($return,JSON_UNESCAPED_UNICODE);


// 서버 실제 업데이트
} else if ($type == 'new_update') {
	// 필요변수 :  $type, $no, $pure_str, $dbi,  $yako, $english, $korean, $extra
    // 수행 절차 :
    // - 타이틀 스트링 정제
    // - 편집일 조정
    // - 타이틀,편집일 업데이트 쿼리
    // - 타이틀(약어,영어,한글,기타)을 dict_word_list 삽입
    // - 편집일 업데이트 후 select 결과 보이기
    // - 요약(synopsis) 업데이트
    // - cjb_dict abbr 업데이트
    // - dict_anchor abbr 업데이트
    // - dict_anchor abbr 화면출력
    // - http 헤더 (json 포멧) 
    // - 메세지들을 json 포멧화시켜 결과 송출

    // 타이틀 스트링 정제
    $trans = [" ,",", "];
    $yako = mysqli_real_escape_string($dbi,trim(str_replace($trans,",",$yako)));
    $english = mysqli_real_escape_string($dbi,trim(str_replace($trans,",",$english)));
    $korean = mysqli_real_escape_string($dbi,trim(str_replace($trans,",",$korean)));
    $extra = mysqli_real_escape_string($dbi,trim(str_replace($trans,",",$extra)));

	// 편집 날짜
	if ($sujung=='1') $sujung= ", sujung=sysdate()";	// 현재 날짜 그대로
	elseif ($sujung>0 and $sujung<=90) $sujung= ", sujung=date_sub(sysdate(), interval {$sujung} day)"; // 이전 날짜
	elseif ($sujung == '0') $sujung= ""; // 날짜 변경 없음

    // 타이틀,편집일 업데이트 쿼리
    $set_value = " yako='{$yako}'," 
					. " full_name='{$english}'," 
					. " korean='{$korean}'," 
					. " extra_keyword='{$extra}' "
					. " {$sujung} ";
    $query = "update cjb_dict set {$set_value} where no=$no";
	$result = mysqli_query($dbi, $query);
		if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }

	if (mysqli_affected_rows($dbi) > 0) $msg .= "\n 타이틀,편집일 업데이트 됨";
	else $msg .= "\n 타이틀,편집일 업데이트 되지는 않음 (동일)";

    // dict_word_list에, 기존 것들을 삭제하고, 새로이 업데이트된 것들을 삽입
    $msg .= wordListUpdate ($no,$yako,$english,$korean,$extra,$dbi);

   	// 편집일 업데이트 후 select 결과 보이기
    $query = "select date_format(a.sujung,'%Y-%m-%d') as date from cjb_dict a left join dict_anchor b on a.no=b.no where a.no=$no";
	$result = mysqli_query($dbi,$query);
		if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
   	$matched = mysqli_fetch_assoc($result);
	$date = $matched[date];

    // synopsis update
	$synopsis = synopsis_extract($pure_str);
	$synopsis = mysqli_real_escape_string($dbi,$synopsis);
	$query = "update cjb_dict set synopsis='{$synopsis}' where no=$no";
	$result = mysqli_query($dbi,$query);
		if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }

	// cjb_dict abbr 업데이트
	$abbr = mysqli_real_escape_string($dbi,$pure_str);
	$query = "update cjb_dict set abbr='$abbr' where no=$no";
	$result = mysqli_query($dbi,$query);
		if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
	if (mysqli_affected_rows($dbi) > 0) $msg .= "\n cjb_dict abbr 텍스트가 업데이트 됨";
	else $msg .= "\n cjb_dict abbr 텍스트가 업데이트 되지는 않음 (동일)";

	// dict_anchor abbr 업데이트
	include_once '../reform/file_transform_v2.php';
	$trans_abbr = string_transform($pure_str, $dbi, $no);

	$abbr = mysqli_real_escape_string($dbi,$trans_abbr);
	$query = "update dict_anchor set abbr='$abbr' where no=$no";
	$result = mysqli_query($dbi,$query);
		if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
	if (mysqli_affected_rows($dbi) > 0) $msg .= "\n dict_anchor abbr 업데이트 됨";
	else $msg .= "\n dict_anchor abbr 텍스트가 업데이트 되지는 않음 (동일)";

	// dict_anchor abbr 화면출력
	include_once "../view/view_body_text.php";
	$abbr = body_text_return ($no, $trans_abbr, '', $dbi);

    // http 헤더 (json 포멧)
    header('content-type: application/json; charset=utf-8');

	// 메세지들을 json 포멧화시켜 결과 송출
	$return = array('msg'=>$msg,'abbr'=>$abbr,'date'=>$date);
    echo json_encode($return,JSON_UNESCAPED_UNICODE);


// 타이틀 업데이트
} else if ($type == 'title_update') {

    // http 헤더 (json 포멧)
    header('content-type: application/json; charset=utf-8');

    // 전달된 타이틀 스트링 정제
    $trans = [" ,",", "];
    $yako = mysqli_real_escape_string($dbi,trim(str_replace($trans,",",$yako)));
    $english = mysqli_real_escape_string($dbi,trim(str_replace($trans,",",$english)));
    $korean = mysqli_real_escape_string($dbi,trim(str_replace($trans,",",$korean)));
    $extra = mysqli_real_escape_string($dbi,trim(str_replace($trans,",",$extra)));

    // 업데이트 쿼리
    $set_value = " yako='{$yako}'," . " full_name='{$english}'," . " korean='{$korean}'," . " extra_keyword='{$extra}' ";
//                . ", sujung=sysdate()";
    $query = "update cjb_dict set {$set_value} where no=$no";
	$result = mysqli_query($dbi,$query);
		if (mysqli_errno($dbi)) { echo mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }

	// title select 및 결과 보이기
		$query = "select * from cjb_dict where no=$no";
		$result = mysqli_query($dbi,$query);
			if (mysqli_errno($dbi)) { echo mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
		if ( $matched = mysqli_fetch_assoc($result) ) {
            $item_str = array('no'=>$matched[no],'yako'=>$matched[yako],'english'=>$matched[full_name],'korean'=>$matched[korean],
                                'extra'=>$matched[extra_keyword],'sujung'=>substr($matched[sujung],0,10));
		} else {
			echo "업데이트 결과 쿼리 실패 !!!";
		}

    // json 포멧으로 송출
    echo json_encode($item_str,JSON_UNESCAPED_UNICODE);

// (구) 편집
} else if ($type == 'old_update') {

	if (!empty($pure_str) and !empty($no)) {

        // http 헤더 (json 포멧)
        header('content-type: application/json; charset=utf-8');

        // 전달된 타이틀 스트링 정제 및 타이틀 각각을 배열화 
        $trans = [" ,",", "];
		$yako = trim(str_replace($trans,",",$yako));
			if(!empty($yako)) $each_arr["y"] = explode(",",$yako);
		$english = trim(str_replace($trans,",",$english));
			if(!empty($english)) $each_arr["f"] = explode(",",$english);
		$korean = trim(str_replace($trans,",",$korean));
			if(!empty($korean)) $each_arr["k"] = explode(",",$korean);
		$extra = trim(str_replace($trans,",",$extra));
			if(!empty($extra)) $each_arr["e"] = explode(",",$extra);

		// 타이틀 각각을 dict_word_list 테이블에 분리 삽입 

			// (기존 delete)
			$query = "delete from dict_word_list where no=$no";
			mysqli_query($dbi,$query);
				if (mysqli_errno($dbi)) echo mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n";

			foreach($each_arr as $key => $value) {
				foreach($value as $word_value) {
				    $word_arr[] = "($no,'{$word_value}','{$key}')";
				}
			}

			// (새로이 insert)
			if (count($word_arr)>0) {
				$query = "insert into dict_word_list (no,word,wordtype) values ".implode(',', $word_arr);
				mysqli_query($dbi,$query);
					if (mysqli_errno($dbi)) echo mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n";
			}

		// 해킹 방어
        $yako = mysqli_real_escape_string($dbi,$yako);
        $english = mysqli_real_escape_string($dbi,$english);
        $korean = mysqli_real_escape_string($dbi,$korean);
        $extra = mysqli_real_escape_string($dbi,$extra);
		$abbr = mysqli_real_escape_string($dbi,$pure_str);

		// 편집 날짜
		if ($sujung=='1') $sujung= ", sujung=sysdate()";	// 현재 날짜 그대로
		elseif ($sujung>0 and $sujung<=90) $sujung= ", sujung=date_sub(sysdate(), interval {$sujung} day)"; // 이전 날짜
		elseif ($sujung == '100') $sujung= ""; // 날짜 변경 없음

        // 타이틀,해설내용 업데이트 쿼리
        $set_value = " yako='{$yako}'" . ", full_name='{$english}'" . ", korean='{$korean}'" . ", extra_keyword='{$extra}'"
                        . ", abbr ='{$abbr}'"
	                    . " {$sujung}";
        $query = "update cjb_dict set {$set_value} where no=$no";
		$result = mysqli_query($dbi,$query);
			if (mysqli_errno($dbi)) { 
				echo mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n";
				return;
			}

		// content update
		include_once '../reform/file_transform_v2.php';
		$abbr = string_transform($pure_str,$dbi,$no);

		$abbr = mysqli_real_escape_string($dbi,$abbr);
		$query = "update dict_anchor set abbr='{$abbr}' where no=$no";
		$result = mysqli_query($dbi,$query);
			if (mysqli_errno($dbi)) { 
				echo mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n";
				return;
			}

        // synopsis update
		$synopsis = synopsis_extract($pure_str);
		$synopsis = mysqli_real_escape_string($dbi,$synopsis);
		$query = "update cjb_dict set synopsis='{$synopsis}' where no=$no";
		$result = mysqli_query($dbi,$query);
			if (mysqli_errno($dbi)) { echo mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }

    	// update 후 select 결과 보이기
	    $query = "select a.no,a.yako,a.full_name,a.korean,a.extra_keyword,a.sujung,b.abbr from cjb_dict a left join dict_anchor b on a.no=b.no where a.no=$no";
		$result = mysqli_query($dbi,$query);
		    if (mysqli_errno($dbi)) { echo mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
    	if ( $matched = mysqli_fetch_assoc($result) ) {
            $item_str = array('no'=>$matched[no],'yako'=>$matched[yako],'english'=>$matched[full_name],'korean'=>$matched[korean],
                                'extra'=>$matched[extra_keyword],'abbr'=>$matched[abbr],'sujung'=>substr($matched[sujung],0,10));
		} else {
		    echo "업데이트 결과 쿼리 실패 !!!";
		}

        // json 포멧으로 송출
        echo json_encode($item_str,JSON_UNESCAPED_UNICODE);

	}

// 실제 업데이트
} else if ($type == 'update') {

    // html 선언
	echo "<!DOCTYPE html>";
	echo "<html>";

	if (!empty($pure_str)) {
		// pure update
		$abbr = mysqli_real_escape_string($dbi,$pure_str);
		$query = "update cjb_dict set abbr='{$abbr}' where no=$no";
		$result = mysqli_query($dbi,$query);
			if (mysqli_errno($dbi)) { 
				echo mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n";
				return;
			}
	
		// content update
		include_once '../reform/file_transform_v2.php';
		$abbr = string_transform($pure_str,$dbi,$no);

		$abbr = mysqli_real_escape_string($dbi,$abbr);
		$query = "update cjb_dict set content='{$abbr}' where no=$no";
		$result = mysqli_query($dbi,$query);
			if (mysqli_errno($dbi)) { 
				echo mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n";
				return;
			}

		// synopsis update
		$synopsis = synopsis($pure_str);
		$synopsis = mysqli_real_escape_string($dbi,$synopsis);
		$query = "update cjb_dict set synopsis='{$synopsis}' where no=$no";
		$result = mysqli_query($dbi,$query);
			if (mysqli_errno($dbi)) { echo mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
	}

	// content select 및 결과 보이기
	$query = "select content from cjb_dict where no=$no";
	$result = mysqli_query($dbi,$query);
		if (mysqli_errno($dbi)) { echo mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
	if ( $matched = mysqli_fetch_assoc($result) ) {
		include_once "../view/view_body_text.php";
		body_text ($no, $matched[content], $imgfilename, $dbi);
//		echo $matched[content];
	} else {
		echo "업데이트 결과 쿼리 실패 !!!";
	}

    // html 닫힘
	echo "</html>";


// 단일 파일 업로드
} else if ($type=='one_upload' and count($_FILES)>0) {

	// 디버깅용
	$msg .= "<pre>".print_r($_FILES,true)."</pre>";
	
	// 파일 업로드 환경
	$target_dir = $_SESSION['img_dir'];
	$fileExtension = strtolower(pathinfo(basename($_FILES["fileToUpload"]["name"]),PATHINFO_EXTENSION));
	$uploadOk = 1;

	// 정보 출력
	$msg .= "<br> 용어해설번호 : ".$no;
	$msg .= "<br> 삽입번호 : ".$in_no;
	$msg .= "<br>" . (empty($_FILES) ? "업로드된 파일 => 없음" : "업로드된 파일 => 있음");
	$msg .= "<br> 임시 업로드 원본 파일 명칭 : " . $_FILES["fileToUpload"]["name"];
	$msg .= "<br> 임시 업로드 원본 파일 확장자 : " . $fileExtension;
	$msg .= "<br> 임시 업로드 파일 명칭 : " . $_FILES["fileToUpload"]["tmp_name"];

	$msg .= "<br> 파일 종류 : " . $_FILES["fileToUpload"]["type"];

	// 이미지 파일 여부 체크
	$imageCheck = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
	if ($imageCheck !== false) {
		$msg .= "<br> 이미지 파일 종류 : " . $imageCheck['mime'];
	} else {
		$msg .= "<br> 이미지 파일 아님";
	    $uploadOk = 0;
	}

	// 파일 크기 체크
	$msg .= "<br> 파일 크기 : " . $_FILES["fileToUpload"]["size"] . " bytes";
	if ($_FILES["fileToUpload"]["size"] > 500000) {
		$uploadOk = 0;
		$msg .= "<br> 이미지 파일 크기 초과";
	}
	
	// 최종 업로드 경로 및 파일명
	$imgFileName = $no."_".$in_no.".".$fileExtension;
	$file_path = $target_dir . $imgFileName;
	$msg .= "<br> 업로드시킬 경로 및 파일명 : " . $file_path;

	// 파일 업로드 완결
	if ($uploadOk == 1) {
		if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $file_path)) {
		    $msg .= "<br> 원래 파일 ".basename( $_FILES["fileToUpload"]["name"])."이 ".$imgFileName."로 업로드 됨";
			$msg .= "<br>";
			$msg .= "<img src='/img_data/{$imgFileName}?".time()."' />";	// image no cache
		} else {
			$msg .= "<br> 파일 업로드 에러";
		}
	} else {
		$msg .= "<br> 파일 업로드 거부";
	}

	// 업데이트
	$query = "update embed set origin='{$imgFileName}' where no=$no and in_no=$in_no and type='g'";
	$msg .= "<br>".$query;
	$result = mysqli_query($dbi,$query);
		if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
	if (mysqli_affected_rows($dbi) > 0) $msg .= "<br> embed 테이블 성공적으로 업데이트됨";

    // http 헤더 (json 포멧)
    header('content-type: application/json; charset=utf-8');

	// 메세지들을 json 포멧화시켜 결과 송출
	$return = array('msg'=>$msg, 'filepath'=>'/img_data/'.$imgFileName);
    echo json_encode($return,JSON_UNESCAPED_UNICODE);	


// mathjax 수식 업데이트
} else if ($type == 'math_edit') {
	// 필요 변수 : $type, $no, $in_no, $pure_str, $dbi
	$msg = " type = {$type} \n no = {$no} \n in_no = {$in_no} \n pure_str = {$pure_str}";

	// 기존 존재 여부 쿼리
	$query = "select no,code from embed where no=$no and in_no=$in_no";
	$result = mysqli_query($dbi,$query);
		if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }

	// mathjax 업데이트
	if (mysqli_num_rows($result) > 0) {
		$msg .= "\n 현재 {$no},{$in_no}가 embed 테이블에 있음";
		// 해킹 방어
		$orig_str = $pure_str;
		$pure_str = mysqli_real_escape_string($dbi, $pure_str);

		$query = "update embed set type='m',code='{$pure_str}' where no=$no and in_no=$in_no";
		$result = mysqli_query($dbi,$query);
			if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
		if (mysqli_affected_rows($dbi) > 0) {
			$msg .= "<br> embed 테이블에 성공적으로 업데이트됨";
			$math = $orig_str; 
		}
		$available_in_no = $in_no;

	// mathjax 추가
	} else {
		$msg .= "\n 현재 {$no},{$in_no}가 embed 테이블에 없음";
		// in_no 중 빈 번호 찾아냄
		$query = "select max(in_no) + 1 as available from embed where no=$no";
		$result = mysqli_query($dbi, $query);
			if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
		$matched = mysqli_fetch_assoc($result);

		if (empty($matched[available])) $available_in_no = 1;
		else $available_in_no = $matched[available];
		$msg .= "\n available_in_no=".$available_in_no;

		// 기존 cjb_dict의 abbr에서 mathjax 문자열을 {[(in_no)]}로 교체
		$query = "select abbr from cjb_dict where no=$no limit 1";
		$result = mysqli_query($dbi, $query);
			if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
		$matched = mysqli_fetch_assoc($result);
		
		
		$pure_str_trans = str_replace(chr(10),chr(13).chr(10),$pure_str);	// dos 형식으로 crlf 처리
		$pure_str_trans = str_replace("'","&#039;",$pure_str_trans);			// 단일 따옴표

		// 문자열 교체
		$abbr = str_replace($pure_str_trans,"{[($available_in_no)]}",$matched[abbr],$count);	// 문자열 교체 수 => $count
		$msg .= "\n abbr 내 교체된 문자열 수 =".$count;

		if ($count <= 0) { 
			$pos = strpos($matched[abbr],$pure_str_trans);
			$msg .= "\n pure_str(교체될것 예정)=".$pure_str_trans.", abbr=\n".$matched[abbr]; 
		} else {
			$abbr = mysqli_real_escape_string($dbi,$abbr);
			$query = "update cjb_dict set abbr='{$abbr}' where no=$no limit 1";
			$result = mysqli_query($dbi, $query);
				if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
			if (mysqli_affected_rows($dbi) > 0) 
				$msg .= "\n 기존 cjb_dict의 번호 {$no}의 abbr에서 mathjax 문자열을 {[({$available_in_no})]}로 교체됨";
			else 
				$msg .= "\n 기존 cjb_dict의 번호 {$no}의 abbr에서 mathjax 문자열을 {[({$available_in_no})]}로 교체 못시킴";

			// 해킹 방어
			$orig_str = $pure_str;
			$pure_str = mysqli_real_escape_string($dbi,$pure_str);

			// 삽입
			$query = "insert into embed (no,in_no,type,code) values ($no,$available_in_no,'m','{$pure_str}')";
			$result = mysqli_query($dbi,$query);
				if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
			if (mysqli_affected_rows($dbi) > 0) {
				$msg .= "\n embed 테이블에 번호 {$available_in_no}로써 성공적으로 삽입됨";
				$math = $orig_str;
				$r_type = "converted"; 
			}
		}
	}

    // http 헤더 (json 포멧)
    header('content-type: application/json; charset=utf-8');

	// 메세지들을 json 포멧화시켜 결과 송출
	$return = array('msg'=>$msg,'in_no'=>$available_in_no,'math'=>$math,'r_type'=>$r_type);
    echo json_encode($return,JSON_UNESCAPED_UNICODE);	

// mathjax db화
} else if ($type == 'mathjax_db') {
	// 필요 변수 : $type, $no, $dbi 
	$msg = " type = {$type} \n no = {$no} ";

	// 해당 no의 abbr 추출
	$query = "select a.abbr,b.max_in_no from cjb_dict a left join (select no,max(in_no)+1 as max_in_no from embed where no=$no) b on a.no=b.no where a.no=$no";
	$result = mysqli_query($dbi,$query);
		if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
	$matched = mysqli_fetch_assoc($result);
	$abbr = $matched[abbr];
	$in_no = $matched[max_in_no];

	// 
	if ( strpos($abbr,'[#') !== false or strpos($abbr,'{#') !== false ) { 
		$embed_math_arr = []; 
		$abbr = mathjax_db_process($no, $abbr, $in_no, $embed_math_arr, '{#','#}'); // $embed_arr : call by reference
		$abbr = mathjax_db_process($no, $abbr, $in_no, $embed_math_arr, '[#','#]'); // $embed_arr : call by reference

		if (count($embed_math_arr)>0) {
			// embed 테이블에 배열을 db화하여 삽입
			foreach($embed_math_arr as $key => $value) {
				$code = mysqli_real_escape_string($dbi,$value[code]);
				$insert_values .= "({$value[no]},{$value[in_no]},'{$code}','m')";
				if ($key < (count($embed_math_arr)-1)) $insert_values .= ",";			
			}			

			$query = "insert into embed (no,in_no,code,type) values {$insert_values}";
			$msg .= "\n ".$query;
			$result = mysqli_query($dbi,$query);
				if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }

			// 현재 cjb_dict의 abbr에 변경값들({[(x)]}) 업데이트
			$abbr = mysqli_real_escape_string($dbi,$abbr);
			$query = "update cjb_dict set abbr='{$abbr}' where no=$no";
			$msg .= "\n ".$query;
			$result = mysqli_query($dbi,$query);
				if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }

			// cjb_dict의 abbr 화면 표출
			$query = "select a.no, yako, full_name, korean, extra_keyword, sujung, a.abbr as orig_text, b.abbr as disp,
						content, content_orig, c.in_no, c.type, c.origin, c.text, c.code
						from cjb_dict a left join dict_anchor b on a.no=b.no left join embed c on a.no=c.no where a.no=$no";
			$result = mysqli_query($dbi, $query);
				if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
			while ($matched = mysqli_fetch_assoc($result)) {
				$embed_all_arr[] = $matched; 
					// no, in_no, type, origin, text, code
			}
			include "../edit/edit_utils.php";
			$display_arr = text_display ($embed_all_arr[0][orig_text], $embed_all_arr);

		}

	} else {
		$msg = "\n 용어해설 중에 mathjax 포함 없음";
	} 

    // http 헤더 (json 포멧)
    header('content-type: application/json; charset=utf-8');

	// 메세지들을 json 포멧화시켜 결과 송출
	$return = array('msg'=>$msg,'abbr'=>$display_arr[abbr],'math_arr'=>$embed_math_arr);
    echo json_encode($return,JSON_UNESCAPED_UNICODE);


// link_update
} else if ($type == 'link_update') {
	// 필요 변수 : $type, $no, $in_no, $edit_str, $pure_str, $dbi 
	$msg = " type = {$type} \n no = {$no} \n in_no = {$in_no} \n edit_str = {$edit_str} \n pure_str = {$pure_str} ";

	$link = mysqli_real_escape_string($dbi,$edit_str);
	$text = mysqli_real_escape_string($dbi,$pure_str);
	$query = "update embed set origin='{$link}',text='{$text}' where no=$no and in_no=$in_no limit 1";
	$msg .= "\n ".$query;
	$result = mysqli_query($dbi,$query);
		if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
	if (mysqli_affected_rows($dbi) > 0) {
		$msg .= "\n 실제 link 업데이트가 이루어짐";
		$query = "select origin,text from embed where no=$no and in_no=$in_no limit 1";
		$result = mysqli_query($dbi,$query);
			if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
		$matched = mysqli_fetch_assoc($result);
		$link_out = $matched[origin];
		$text_out = $matched[text];
	} else $msg .= "\n 실제 link 업데이트는 이루어지지 않음";

    // http 헤더 (json 포멧)
    header('content-type: application/json; charset=utf-8');

	// 메세지들을 json 포멧화시켜 결과 송출
	$return = array('msg'=>$msg,'link'=>$link_out,'text'=>$text_out);
    echo json_encode($return,JSON_UNESCAPED_UNICODE);

}

?>

<?php
// 전 처리
function pre_processing($rest) {
	// '<img ' ~ '>' 제거
	$rest = pair_delimiter($rest,'<img ','>');
	// mathjax 제거
	$rest = pair_delimiter($rest,"<div style='display:inline-block;'>","<div>");
	return $rest;
}

// 시간 측정 (php 5.xx대에서 에러? 같음)
function microtime_float() {
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

// mathjax db화를 위한 전처리 배열화
function mathjax_db_process($no, $abbr, &$in_no, &$embed_arr, $left, $right) {

	$right_pos=0;
	while ( ($left_pos=strpos($abbr,$left,$right_pos)) and ($right_pos=strpos($abbr,$right,$left_pos)) ) {
		$left_str = substr($abbr,0,$left_pos);
		$right_str = substr($abbr,$right_pos+strlen($right));

		$middle_str = substr($abbr,$left_pos,$right_pos-$left_pos+strlen($right));
		$pure_str = substr($abbr,$left_pos+strlen($left),$right_pos-$left_pos-strlen($left));

		$embed_arr[] = array('no'=>$no, 'in_no'=>$in_no, 'code'=>$middle_str, 'type'=>'m');

		$replaced_str = '{[('.$in_no.')]}';
		$abbr = $left_str . $replaced_str . $right_str;
		$right_pos = $left_pos + strlen($replaced_str);
		$in_no += 1;
	}
	return $abbr;
}

function wordListUpdate ($no,$yako,$english,$korean,$extra,$dbi) {

    $wordArr = array();

    if(!empty($yako)) $wordArr = array_merge($wordArr, wordExplode($no,$yako,$dbi,'y'));
    if(!empty($english)) $wordArr = array_merge($wordArr, wordExplode($no,$english,$dbi,'f'));
    if(!empty($korean)) $wordArr = array_merge($wordArr, wordExplode($no,$korean,$dbi,'k'));
    if(!empty($extra)) $wordArr = array_merge($wordArr, wordExplode($no,$extra,$dbi));

    $query = "delete from dict_word_list where no=$no";
    mysqli_query($dbi, $query); 
		if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }

    $query = "INSERT INTO dict_word_list (no, word, wordtype) values ";
    $query .= implode(',', $wordArr);
    mysqli_query($dbi, $query); 
  		if (mysqli_errno($dbi)) { $msg .= mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n"; }
    return $msg;
}


function wordExplode($no, $wordList, $dbi, $wordType='') {
    $wordList = str_replace('  ',' ',trim($wordList));
    $wordExplode = explode(',',$wordList);
    foreach($wordExplode as $value) {
        if(!empty($value)) {
            $value = trim($value);
            if(empty($wordType)) {
                // 한글(k), 영어(f)
//                $wordType = ( preg_match('/[\x{ac00}-\x{d7a3}][\x{ac00}-\x{d7a3}]/u', $value) ? 'k' : 'f' );
                $type = preg_match('/[\x{ac00}-\x{d7a3}]/u',$value) ? 'k' : 'f';
            } else 
                $type = $wordType;
            $value = mysqli_real_escape_string($dbi, $value);
            $resultArr[] = "('{$no}', '{$value}', '{$type}')";
        }
    }
    return $resultArr;
}

?>


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