forked from gnuboard/g4dtd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.lib.php
1567 lines (1283 loc) · 48.1 KB
/
common.lib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
if (!defined('_GNUBOARD_')) exit;
/*************************************************************************
**
** 일반 함수 모음
**
*************************************************************************/
// 마이크로 타임을 얻어 계산 형식으로 만듦
function get_microtime()
{
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
/**
* @brief 디버그 메시지 출력
* XpressEngine의 코드 차용. http://xpressengien.com/
**/
function debugPrint($debug_output = null) {
$bt = debug_backtrace();
if(is_array($bt)) $first = array_shift($bt);
$file_name = $first['file'];
$line_num = $first['line'];
$debug_file = $g4['path'].'/data/_debug_message.php';
$debug_output = sprintf("[%s %s:%d]\n%s\n",
date('Y-m-d H:i:s'),
$file_name,
$line_num,
print_r($debug_output, true)
);
$debug_output = '<?php exit(); ?>'.str_repeat('=', 40)."\n".$debug_output.str_repeat('-', 40)."\n\n";
$fp = @fopen($debug_file, 'a');
if(!$fp) return;
fwrite($fp, $debug_output);
fclose($fp);
}
// 현재페이지, 총페이지수, 한페이지에 보여줄 행, URL
function get_paging($write_pages, $cur_page, $total_page, $url, $add="")
{
$str = "";
if ($cur_page > 1) {
$str .= "<a href='" . $url . "1{$add}'>처음</a>";
//$str .= "[<a href='" . $url . ($cur_page-1) . "'>이전</a>]";
}
$start_page = ( ( (int)( ($cur_page - 1 ) / $write_pages ) ) * $write_pages ) + 1;
$end_page = $start_page + $write_pages - 1;
if ($end_page >= $total_page) $end_page = $total_page;
if ($start_page > 1) $str .= " <a href='" . $url . ($start_page-1) . "{$add}'>이전</a>";
if ($total_page > 1) {
for ($k=$start_page;$k<=$end_page;$k++) {
if ($cur_page != $k)
$str .= " <a href='$url$k{$add}'><span>$k</span></a>";
else
$str .= " <strong>$k</strong> ";
}
}
if ($total_page > $end_page) $str .= " <a href='" . $url . ($end_page+1) . "{$add}'>다음</a>";
if ($cur_page < $total_page) {
//$str .= "[<a href='$url" . ($cur_page+1) . "'>다음</a>]";
$str .= " <a href='$url$total_page{$add}'>맨끝</a>";
}
$str .= "";
return $str;
}
// 변수 또는 배열의 이름과 값을 얻어냄. print_r() 함수의 변형
function print_r2($var)
{
ob_start();
print_r($var);
$str = ob_get_contents();
ob_end_clean();
$str = preg_replace("/ /", " ", $str);
echo nl2br("<span style='font-family:Tahoma, 굴림; font-size:9pt;'>$str</span>");
}
// 메타태그를 이용한 URL 이동
// header("location:URL") 을 대체
function goto_url($url)
{
echo "<meta http-equiv=\"content-type\" content=\"text/html; charset={$g4['charset']}\">";
echo "<script type='text/javascript'> location.replace('$url'); </script>";
exit;
}
// 세션변수 생성
function set_session($session_name, $value)
{
if (PHP_VERSION < '5.3.0')
session_register($session_name);
// PHP 버전별 차이를 없애기 위한 방법
$$session_name = $_SESSION["$session_name"] = $value;
}
// 세션변수값 얻음
function get_session($session_name)
{
return $_SESSION[$session_name];
}
// 쿠키변수 생성
function set_cookie($cookie_name, $value, $expire)
{
global $g4;
setcookie(md5($cookie_name), base64_encode($value), $g4['server_time'] + $expire, '/', $g4['cookie_domain']);
}
// 쿠키변수값 얻음
function get_cookie($cookie_name)
{
return base64_decode($_COOKIE[md5($cookie_name)]);
}
// 경고메세지를 경고창으로
function alert($msg='', $url='')
{
global $g4;
if (!$msg) $msg = '올바른 방법으로 이용해 주십시오.';
echo "<meta http-equiv=\"content-type\" content=\"text/html; charset={$g4['charset']}\">";
echo "<script type='text/javascript'>alert('$msg');";
if (!$url)
echo "history.go(-1);";
echo "</script>";
if ($url)
goto_url($url);
exit;
}
// 경고메세지 출력후 창을 닫음
function alert_close($msg)
{
global $g4;
echo "<meta http-equiv=\"content-type\" content=\"text/html; charset={$g4['charset']}\">";
echo "<script type='text/javascript'> alert('$msg'); window.close(); </script>";
exit;
}
// way.co.kr 의 wayboard 참고
function url_auto_link($str)
{
global $config;
$str = preg_replace("/</", "\t_lt_\t", $str);
$str = preg_replace("/>/", "\t_gt_\t", $str);
$str = preg_replace("/&/", "&", $str);
$str = preg_replace("/"/", "\"", $str);
$str = preg_replace("/ /", "\t_nbsp_\t", $str);
$str = preg_replace("/([^(http:\/\/)]|\(|^)(www\.[^[:space:]]+)/i", "\\1<A HREF=\"http://\\2\" TARGET='{$config['cf_link_target']}'>\\2</A>", $str);
$str = preg_replace("/([^(HREF=\"?'?)|(SRC=\"?'?)]|\(|^)((http|https|ftp|telnet|news|mms):\/\/[a-zA-Z0-9\.-]+\.[가-힣\xA1-\xFEa-zA-Z0-9\.:&#=_\?\/~\+%@;\-\|\,\(\)]+)/i", "\\1<A HREF=\"\\2\" TARGET='{$config['cf_link_target']}'>\\2</A>", $str);
$str = preg_replace("/([0-9a-z]([-_\.]?[0-9a-z])*@[0-9a-z]([-_\.]?[0-9a-z])*\.[a-z]{2,4})/i", "<a href='mailto:\\1'>\\1</a>", $str);
$str = preg_replace("/\t_nbsp_\t/", " " , $str);
$str = preg_replace("/\t_lt_\t/", "<", $str);
$str = preg_replace("/\t_gt_\t/", ">", $str);
return $str;
}
// url에 http:// 를 붙인다
function set_http($url)
{
if (!trim($url)) return;
if (!preg_match("/^(http|https|ftp|telnet|news|mms)\:\/\//i", $url))
$url = "http://" . $url;
return $url;
}
// 파일의 용량을 구한다.
function get_filesize($size)
{
//$size = @filesize(addslashes($file));
if ($size >= 1048576) {
$size = number_format($size/1048576, 1) . "M";
} else if ($size >= 1024) {
$size = number_format($size/1024, 1) . "K";
} else {
$size = number_format($size, 0) . "byte";
}
return $size;
}
// 게시글에 첨부된 파일을 얻는다. (배열로 반환)
function get_file($bo_table, $wr_id, $board)
{
global $g4, $qstr;
$file["count"] = 0;
$sql = " select * from {$g4['board_file_table']} where bo_table = '$bo_table' and wr_id = '$wr_id' order by bf_no ";
$result = sql_query($sql);
while ($row = sql_fetch_array($result))
{
$no = $row['bf_no'];
$file[$no]['href'] = "./download.php?bo_table=$bo_table&wr_id=$wr_id&no=$no" . $qstr;
$file[$no]['download'] = $row['bf_download'];
$file[$no]['path'] = "{$g4['path']}/data/file/$bo_table";
$file[$no]['size'] = get_filesize($row['bf_filesize']);
$file[$no]['datetime'] = $row['bf_datetime'];
$file[$no]['source'] = addslashes($row['bf_source']);
$file[$no]['bf_content'] = $row['bf_content'];
$file[$no]['content'] = get_text($row['bf_content']);
$file[$no]['view'] = view_file_link($row['bf_file'], $row['bf_width'], $row['bf_height'], $file[$no]['content'], $board);
$file[$no]['file'] = $row['bf_file'];
$file[$no]['image_width'] = $row['bf_width'] ? $row['bf_width'] : 640;
$file[$no]['image_height']= $row['bf_height'] ? $row['bf_height'] : 480;
$file[$no]['image_type'] = $row['bf_type'];
$file["count"]++;
}
return $file;
}
// 폴더의 용량 ($dir는 / 없이 넘기세요)
function get_dirsize($dir)
{
$size = 0;
$d = dir($dir);
while ($entry = $d->read()) {
if ($entry != "." && $entry != "..") {
$size += filesize("$dir/$entry");
}
}
$d->close();
return $size;
}
/*************************************************************************
**
** 그누보드 관련 함수 모음
**
*************************************************************************/
// 게시물 정보($write_row)를 출력하기 위하여 $list로 가공된 정보를 복사 및 가공
function get_list($write_row, $board, $skin_path, $subject_len=40)
{
global $g4, $config;
global $qstr, $page;
// 배열전체를 복사
$list = $write_row;
unset($write_row);
$list['is_notice'] = preg_match("/[^0-9]{0,1}" .$list['wr_id'] . "[\r]{0,1}/",$board['bo_notice']);
if ($subject_len)
$list['subject'] = conv_subject($list['wr_subject'], $subject_len, "…");
else
$list['subject'] = conv_subject($list['wr_subject'], $board['bo_subject_len'], "…");
// 목록에서 내용 미리보기 사용한 게시판만 내용을 변환함 (속도 향상) : kkal3(커피)님께서 알려주셨습니다.
if ($board['bo_use_list_content'])
{
$html = 0;
if (strstr($list['wr_option'], "html1"))
$html = 1;
else if (strstr($list['wr_option'], "html2"))
$html = 2;
$list['content'] = conv_content($list['wr_content'], $html);
}
$list['comment_cnt'] = "";
if ($list['wr_comment'])
$list['comment_cnt'] = "({$list['wr_comment']})";
// 당일인 경우 시간으로 표시함
$list['datetime'] = substr($list['wr_datetime'],0,10);
$list['datetime2'] = $list['wr_datetime'];
if ($list['datetime'] == $g4['time_ymd'])
$list['datetime2'] = substr($list['datetime2'],11,5);
else
$list['datetime2'] = substr($list['datetime2'],5,5);
// 4.1
$list['last'] = substr($list['wr_last'],0,10);
$list['last2'] = $list['wr_last'];
if ($list['last'] == $g4['time_ymd'])
$list['last2'] = substr($list['last2'],11,5);
else
$list['last2'] = substr($list['last2'],5,5);
$list['wr_homepage'] = get_text(addslashes($list['wr_homepage']));
if ($board['bo_use_sideview'])
$list['name'] = get_sideview($list['mb_id'], $list['wr_name'], $list['wr_email'], $list['wr_homepage']);
else
$list['name'] = "<span class='".($list['mb_id']?'member':'guest')."'>{$list['wr_name']}</span>";
$reply = $list['wr_reply'];
$list['reply'] = "";
if (strlen($reply) > 0)
{
for ($k=0; $k<strlen($reply); $k++)
$list['reply'] .= "<span class='reply'></span>";
}
$list['icon_reply'] = "";
if ($list['reply'])
$list['icon_reply'] = "<img src='$skin_path/img/icon_reply.gif' alt='' class='icon_reply' />";
$list['icon_link'] = "";
if ($list['wr_link1'] || $list['wr_link2'])
$list['icon_link'] = "<img src='$skin_path/img/icon_link.gif' alt='' />";
// 분류명 링크
$list['ca_name_href'] = "{$g4['bbs_path']}/board.php?bo_table={$board['bo_table']}&sca=".urlencode($list['ca_name']);
$list['href'] = "{$g4['bbs_path']}/board.php?bo_table={$board['bo_table']}&wr_id={$list['wr_id']}" . $qstr;
$list['comment_href'] = $list['href'];
$list['icon_new'] = "";
if ($list['wr_datetime'] >= date("Y-m-d H:i:s", $g4['server_time'] - ($board['bo_new'] * 3600)))
$list['icon_new'] = "<img src='$skin_path/img/icon_new.gif' alt='' />";
$list['icon_hot'] = "";
if ($list['wr_hit'] >= $board['bo_hot'])
$list['icon_hot'] = "<img src='$skin_path/img/icon_hot.gif' alt='' />";
$list['icon_secret'] = "";
if (strstr($list['wr_option'], "secret"))
$list['icon_secret'] = "<img src='$skin_path/img/icon_secret.gif' alt='' />";
// 링크
for ($i=1; $i<=$g4['link_count']; $i++)
{
$list['link'][$i] = set_http(get_text($list["wr_link{$i}"]));
$list['link_href'][$i] = "{$g4['bbs_path']}/link.php?bo_table={$board['bo_table']}&wr_id={$list['wr_id']}&no=$i" . $qstr;
$list['link_hit'][$i] = (int)$list["wr_link{$i}_hit"];
}
// 가변 파일
if ($list['wr_file'])
$list['file'] = get_file($board['bo_table'], $list['wr_id'], $board);
if ($list['file']['count'])
$list['icon_file'] = "<img src='$skin_path/img/icon_file.gif' alt='' />";
return $list;
}
// get_list 의 alias
function get_view($write_row, $board, $skin_path, $subject_len=125)
{
return get_list($write_row, $board, $skin_path, $subject_len);
}
// set_search_font(), get_search_font() 함수를 search_font() 함수로 대체
function search_font($stx, $str)
{
global $config;
// 문자앞에 \ 를 붙입니다.
$src = array("/", "|");
$dst = array("\/", "\|");
if (!trim($stx)) return $str;
// 검색어 전체를 공란으로 나눈다
$s = explode(" ", $stx);
// "/(검색1|검색2)/i" 와 같은 패턴을 만듬
$pattern = "";
$bar = "";
for ($m=0; $m<count($s); $m++) {
if (trim($s[$m]) == "") continue;
// 태그는 포함하지 않아야 하는데 잘 안되는군. ㅡㅡa
//$pattern .= $bar . '([^<])(' . quotemeta($s[$m]) . ')';
//$pattern .= $bar . quotemeta($s[$m]);
//$pattern .= $bar . str_replace("/", "\/", quotemeta($s[$m]));
$tmp_str = quotemeta($s[$m]);
$tmp_str = str_replace($src, $dst, $tmp_str);
$pattern .= $bar . $tmp_str . "(?![^<]*>)";
$bar = "|";
}
// 지정된 검색 폰트의 색상, 배경색상으로 대체
$replace = "<span style='background-color:{$config['cf_search_bgcolor']}; color:{$config['cf_search_color']};'>\\1</span>";
return preg_replace("/($pattern)/i", $replace, $str);
}
// 제목을 변환
function conv_subject($subject, $len, $suffix="")
{
return cut_str(get_text($subject), $len, $suffix);
}
// OBJECT 태그의 XSS 막기
function bad120422($matches)
{
$code = $matches[1];
if (preg_match("#script#i", $code)) {
return "OBJECT 태그에 스크립트는 사용 불가합니다.";
} else if (preg_match("#base64#i", $code)) {
return "OBJECT 태그에 BASE64는 사용 불가합니다.";
}
}
// 내용을 변환
function conv_content($content, $html)
{
global $config, $board;
if ($html)
{
$source = array();
$target = array();
$source[] = "//";
$target[] = "";
if ($html == 2) { // 자동 줄바꿈
$source[] = "/\n/";
$target[] = "<br/>";
}
// 테이블 태그의 갯수를 세어 테이블이 깨지지 않도록 한다.
$table_begin_count = substr_count(strtolower($content), "<table");
$table_end_count = substr_count(strtolower($content), "</table");
for ($i=$table_end_count; $i<$table_begin_count; $i++)
{
$content .= "</table>";
}
$content = preg_replace($source, $target, $content);
$content = bad_tag_convert($content);
// XSS (Cross Site Script) 막기
// 완벽한 XSS 방지는 없다.
// object 태그에서 javascript 코드 막기
$content = preg_replace_callback("#<object([^>]+)>#i", "bad120422", $content);
// 081022 : CSRF 방지
//$content = preg_replace("/(on)(abort|blur|change|click|dblclick|dragdrop|error|focus|keydown|keypress|keyup|load|mousedown|mousemove|mouseout|mouseover|mouseup|mouseenter|mouseleave|move|reset|resize|select|submit|unload)/i", "$1<!-- XSS Filter -->$2", $content);
//$content = preg_replace("/(on)([^\=]+)/i", "on$2", $content);
// 이런 경우를 방지함 <IMG STYLE="xss:expr/*XSS*/ession(alert('XSS'))">
$content = preg_replace("#\/\*.*\*\/#iU", "", $content);
$content = preg_replace("/(on)([a-z]+)([^a-z]*)(\=)/i", "on$2$3$4", $content);
$content = preg_replace("/(dy)(nsrc)/i", "dy$2", $content);
$content = preg_replace("/(lo)(wsrc)/i", "lo$2", $content);
$content = preg_replace("/(sc)(ript)/i", "sc$2", $content);
//$content = preg_replace("/(ex)(pression)/i", "ex$2", $content);
$content = preg_replace("/\<(\w|\s|\?)*(xml)/i", "", $content);
// 이미지 태그의 src 속성에 삭제등의 링크가 있는 경우 게시물을 확인하는 것만으로도 데이터의 위변조가 가능하므로 이것을 막음
$content = preg_replace("/<(img[^>]+delete\.php[^>]+bo_table[^>]+)/i", "*** CSRF 감지 : <$1", $content);
$content = preg_replace("/<(img[^>]+delete_comment\.php[^>]+bo_table[^>]+)/i", "*** CSRF 감지 : <$1", $content);
$content = preg_replace("/<(img[^>]+logout\.php[^>]+)/i", "*** CSRF 감지 : <$1", $content);
$content = preg_replace("/<(img[^>]+download\.php[^>]+bo_table[^>]+)/i", "*** CSRF 감지 : <$1", $content);
// 이런 경우를 방지함 <IMG STYLE="xss:expr/*XSS*/ession(alert('XSS'))">
//$content = preg_replace("#\/\*.*\*\/#iU", "", $content); // 이 코드를 위로 올립니다.
$pattern = "";
$pattern .= "(e|&#(x65|101);?)";
$pattern .= "(x|&#(x78|120);?)";
$pattern .= "(p|&#(x70|112);?)";
$pattern .= "(r|&#(x72|114);?)";
$pattern .= "(e|&#(x65|101);?)";
$pattern .= "(s|&#(x73|115);?)";
$pattern .= "(s|&#(x73|115);?)";
$pattern .= "(i|&#(x6a|105);?)";
$pattern .= "(o|&#(x6f|111);?)";
$pattern .= "(n|&#(x6e|110);?)";
$content = preg_replace("/".$pattern."/i", "__EXPRESSION__", $content);
/*
$content = preg_replace("/\#/", "#", $content);
$content = preg_replace("/\</", "<", $content);
$content = preg_replace("/\>/", ">", $content);
$content = preg_replace("/\(/", "(", $content);
$content = preg_replace("/\)/", ")", $content);
*/
}
else // text 이면
{
// & 처리 : & 등의 코드를 정상 출력함
$content = html_symbol($content);
// 공백 처리
$content = str_replace(" ", " ", $content);
$content = str_replace("\n ", "\n ", $content);
$content = get_text($content, 1);
$content = url_auto_link($content);
}
return $content;
}
// 검색 구문을 얻는다.
function get_sql_search($search_ca_name, $search_field, $search_text, $search_operator='and')
{
global $g4;
$str = "";
if ($search_ca_name)
$str = " ca_name = '$search_ca_name' ";
// 게시판에서 \ 를 검색할 수 있도록 수정
$search_text = trim(stripslashes($search_text));
if (!$search_text)
return $str;
if ($str)
$str .= " and ";
// 쿼리의 속도를 높이기 위하여 ( ) 는 최소화 한다.
$op1 = "";
// 검색어를 구분자로 나눈다. 여기서는 공백
$s = array();
$s = explode(" ", strip_tags($search_text));
// 검색필드를 구분자로 나눈다. 여기서는 +
//$field = array();
//$field = explode("||", trim($search_field));
$tmp = array();
$tmp = explode(",", trim($search_field));
$field = explode("||", $tmp[0]);
$not_comment = $tmp[1];
if(trim($tmp[0]) == "")
{
$str .= "(1)";
}
else
{
$str .= "(";
for ($i=0; $i<count($s); $i++) {
// 검색어
$search_str = trim($s[$i]);
if ($search_str == "") continue;
/*
인기검색어 기능 삭제 : 101202
// 인기검색어
$sql = " insert into {$g4['popular_table']} set pp_word = '$search_str', pp_date = '{$g4['time_ymd']}', pp_ip = '{$_SERVER['REMOTE_ADDR']}' ";
sql_query($sql, FALSE);
*/
$str .= $op1;
$str .= "(";
$op2 = "";
for ($k=0; $k<count($field); $k++) { // 필드의 수만큼 다중 필드 검색 가능 (필드1+필드2...)
// SQL Injection 방지
// 필드값에 a-z A-Z 0-9 _ , | 이외의 값이 있다면 검색필드를 wr_subject 로 설정한다.
$field[$k] = preg_match("/^[\w\,\|]+$/", $field[$k]) ? $field[$k] : "wr_subject";
$str .= $op2;
switch ($field[$k]) {
case "mb_id" :
case "wr_name" :
$str .= " $field[$k] = '$s[$i]' ";
break;
case "wr_hit" :
case "wr_good" :
case "wr_nogood" :
$str .= " $field[$k] >= '$s[$i]' ";
break;
// 번호는 해당 검색어에 -1 을 곱함
case "wr_num" :
$str .= "$field[$k] = ".((-1)*$s[$i]);
break;
// LIKE 보다 INSTR 속도가 빠름
default :
if (preg_match("/[a-zA-Z]/", $search_str))
$str .= "INSTR(LOWER($field[$k]), LOWER('$search_str'))";
else
$str .= "INSTR({$field[$k]}, '$search_str')";
break;
}
$op2 = " or ";
}
$str .= ")";
//$op1 = ($search_operator) ? ' and ' : ' or ';
$op1 = " $search_operator ";
}
$str .= " ) ";
}
if ($not_comment)
$str .= " and wr_is_comment = '0' ";
return $str;
}
// 게시판 테이블에서 하나의 행을 읽음
function get_write($write_table, $wr_id)
{
return sql_fetch(" select * from $write_table where wr_id = '$wr_id' ");
}
// 게시판의 다음글 번호를 얻는다.
function get_next_num($table)
{
// 가장 작은 번호를 얻어
$sql = " select min(wr_num) as min_wr_num from $table ";
$row = sql_fetch($sql);
// 가장 작은 번호에 1을 빼서 넘겨줌
return (int)($row['min_wr_num'] - 1);
}
// 그룹 설정 테이블에서 하나의 행을 읽음
function get_group($gr_id)
{
global $g4;
return sql_fetch(" select * from {$g4['group_table']} where gr_id = '$gr_id' ");
}
// 회원 정보를 얻는다.
function get_member($mb_id, $fields='*')
{
global $g4;
return sql_fetch(" select $fields from {$g4['member_table']} where mb_id = TRIM('$mb_id') ");
}
// 날짜, 조회수의 경우 높은 순서대로 보여져야 하므로 $flag 를 추가
// $flag : asc 낮은 순서 , desc 높은 순서
// 제목별로 컬럼 정렬하는 QUERY STRING
function subject_sort_link($col, $query_string='', $flag='asc')
{
global $sst, $sod, $sfl, $stx, $page;
$q1 = "sst=$col";
if ($flag == 'asc')
{
$q2 = 'sod=asc';
if ($sst == $col)
{
if ($sod == 'asc')
{
$q2 = 'sod=desc';
}
}
}
else
{
$q2 = 'sod=desc';
if ($sst == $col)
{
if ($sod == 'desc')
{
$q2 = 'sod=asc';
}
}
}
return "<a href='{$_SERVER['PHP_SELF']}?$query_string&$q1&$q2&sfl=$sfl&stx=$stx&page=$page'>";
}
// 관리자 정보를 얻음
function get_admin($admin='super')
{
global $config, $group, $board;
global $g4;
$is = false;
if ($admin == 'board') {
$mb = sql_fetch("select * from {$g4['member_table']} where mb_id in ('{$board['bo_admin']}') limit 1 ");
$is = true;
}
if (($is && !$mb['mb_id']) || $admin == 'group') {
$mb = sql_fetch("select * from {$g4['member_table']} where mb_id in ('{$group['gr_admin']}') limit 1 ");
$is = true;
}
if (($is && !$mb['mb_id']) || $admin == 'super') {
$mb = sql_fetch("select * from {$g4['member_table']} where mb_id in ('{$config['cf_admin']}') limit 1 ");
}
return $mb;
}
// 관리자인가?
function is_admin($mb_id)
{
global $config, $group, $board;
if (!$mb_id) return;
if ($config['cf_admin'] == $mb_id) return 'super';
if ($group['gr_admin'] == $mb_id) return 'group';
if ($board['bo_admin'] == $mb_id) return 'board';
return '';
}
// 분류 옵션을 얻음
// 4.00 에서는 카테고리 테이블을 없애고 보드테이블에 있는 내용으로 대체
function get_category_option($bo_table='')
{
global $g4, $board;
$arr = explode("|", $board['bo_category_list']); // 구분자가 , 로 되어 있음
$str = "";
for ($i=0; $i<count($arr); $i++)
if (trim($arr[$i]))
$str .= "<option value='{$arr[$i]}'>{$arr[$i]}</option>\n";
return $str;
}
// 게시판 그룹을 SELECT 형식으로 얻음
function get_group_select($name, $selected='', $event='')
{
global $g4, $is_admin, $member;
$sql = " select gr_id, gr_subject from {$g4['group_table']} a ";
if ($is_admin == "group") {
$sql .= " left join {$g4['member_table']} b on (b.mb_id = a.gr_admin)
where b.mb_id = '{$member['mb_id']}' ";
}
$sql .= " order by a.gr_id ";
$result = sql_query($sql);
$str = "<select name='$name' $event>";
for ($i=0; $row=sql_fetch_array($result); $i++)
{
$str .= "<option value='{$row['gr_id']}'";
if ($row['gr_id'] == $selected) $str .= " selected='selected'";
$str .= ">{$row['gr_subject']}</option>";
}
$str .= "</select>";
return $str;
}
// '예', '아니오'를 SELECT 형식으로 얻음
function get_yn_select($name, $selected='1', $event='')
{
$str = "<select name='$name' $event>";
if ($selected) {
$str .= "<option value='1' selected>예</option>";
$str .= "<option value='0'>아니오</option>";
} else {
$str .= "<option value='1'>예</option>";
$str .= "<option value='0' selected>아니오</option>";
}
$str .= "</select>";
return $str;
}
// 포인트 부여
function insert_point($mb_id, $point, $content='', $rel_table='', $rel_id='', $rel_action='')
{
global $config;
global $g4;
global $is_admin;
// 포인트 사용을 하지 않는다면 return
if (!$config['cf_use_point']) { return 0; }
// 포인트가 없다면 업데이트 할 필요 없음
if ($point == 0) { return 0; }
// 회원아이디가 없다면 업데이트 할 필요 없음
if ($mb_id == "") { return 0; }
$mb = sql_fetch(" select mb_id from {$g4['member_table']} where mb_id = '$mb_id' ");
if (!$mb['mb_id']) { return 0; }
// 이미 등록된 내역이라면 건너뜀
if ($rel_table || $rel_id || $rel_action)
{
$sql = " select count(*) as cnt from {$g4['point_table']} where mb_id = '$mb_id' and po_rel_table = '$rel_table' and po_rel_id = '$rel_id' and po_rel_action = '$rel_action' ";
$row = sql_fetch($sql);
if ($row['cnt'])
return -1;
}
// 포인트 건별 생성
$sql = " insert into {$g4['point_table']}
set mb_id = '$mb_id',
po_datetime = '{$g4['time_ymdhis']}',
po_content = '".addslashes($content)."',
po_point = '$point',
po_rel_table = '$rel_table',
po_rel_id = '$rel_id',
po_rel_action = '$rel_action' ";
sql_query($sql);
// 포인트 내역의 합을 구하고
$sql = " select sum(po_point) as sum_po_point from {$g4['point_table']} where mb_id = '$mb_id' ";
$row = sql_fetch($sql);
$sum_point = $row['sum_po_point'];
// 포인트 UPDATE
$sql = " update {$g4['member_table']} set mb_point = '$sum_point' where mb_id = '$mb_id' ";
sql_query($sql);
return 1;
}
// 포인트 삭제
function delete_point($mb_id, $rel_table, $rel_id, $rel_action)
{
global $g4;
$result = false;
if ($rel_table || $rel_id || $rel_action)
{
$result = sql_query(" delete from {$g4['point_table']}
where mb_id = '$mb_id'
and po_rel_table = '$rel_table'
and po_rel_id = '$rel_id'
and po_rel_action = '$rel_action' ", false);
// 포인트 내역의 합을 구하고
$sql = " select sum(po_point) as sum_po_point from {$g4['point_table']} where mb_id = '$mb_id' ";
$row = sql_fetch($sql);
$sum_point = $row['sum_po_point'];
// 포인트 UPDATE
$sql = " update {$g4['member_table']} set mb_point = '$sum_point' where mb_id = '$mb_id' ";
$result = sql_query($sql);
}
return $result;
}
// 회원 레이어
function get_sideview($mb_id, $name="", $email="", $homepage="")
{
global $config;
global $g4;
$email = base64_encode($email);
$homepage = set_http($homepage);
$name = preg_replace("/\'/", "", $name);
$name = preg_replace("/\'/", "", $name);
$name = preg_replace("/\"/", """, $name);
$title_name = $name;
$tmp_name = get_text(cut_str($name, $config['cf_cut_name'])); // 설정된 자리수 만큼만 이름 출력
if ($mb_id) {
$tmp_name = "<span class='member'>$tmp_name</span>";
if ($config['cf_use_member_icon']) {
$mb_dir = substr($mb_id,0,2);
$icon_file = "{$g4['path']}/data/member/$mb_dir/$mb_id.gif";
//if (file_exists($icon_file) && is_file($icon_file)) {
if (file_exists($icon_file)) {
//$size = getimagesize($icon_file);
//$width = $size[0];
//$height = $size[1];
$width = $config['cf_member_icon_width'];
$height = $config['cf_member_icon_height'];
$tmp_name = "<img src='$icon_file' style='vertical-align:middle; width:$width; height:$height;' alt='$name' />";
if ($config['cf_use_member_icon'] == 2) // 회원아이콘+이름
$tmp_name = $tmp_name . " <span class='member'>$name</span>";
}
}
$title_mb_id = "[$mb_id]";
} else {
$tmp_name = "<span class='guest'>$tmp_name</span>";
$title_mb_id = "[비회원]";
}
$name = get_text($name);
$email = get_text($email);
$homepage = get_text($homepage);
//return "<a href=\"javascript:showSideView(this, '$mb_id', '$name', '$email', '$homepage');\" title=\"{$title_mb_id}{$title_name}\">$tmp_name</a>";
return "<a href='#' class='sidebox' rel='mb_id={$mb_id}&name={$name}&email={$email}&homepage={$homepage}' onclick='return false;'>$tmp_name</a>";
}
// 파일을 보이게 하는 링크 (이미지, 플래쉬, 동영상)
function view_file_link($file, $width, $height, $content="", $board)
{
global $config;
global $g4;
static $ids;
if (!$file) return;
$ids++;
// 파일의 폭이 게시판설정의 이미지폭 보다 크다면 게시판설정 폭으로 맞추고 비율에 따라 높이를 계산
if ($width > $board['bo_image_width'] && $board['bo_image_width'])
{
$rate = $board['bo_image_width'] / $width;
$width = $board['bo_image_width'];
$height = (int)($height * $rate);
}
// 폭이 있는 경우 폭과 높이의 속성을 주고, 없으면 자동 계산되도록 코드를 만들지 않는다.
if ($width)
$attr = " width='$width' height='$height' ";
else
$attr = "";
if (preg_match("/\.(" .$config['cf_image_extension'] . ")$/i", $file))
{
// 이미지에 속성을 주지 않는 이유는 이미지 클릭시 원본 이미지를 보여주기 위한것임
// 게시판설정 이미지보다 크다면 스킨의 자바스크립트에서 이미지를 줄여준다
$img_file = "{$g4['path']}/data/file/{$board['bo_table']}/".urlencode($file);
$size = getimagesize($img_file);
// 이미지폭이 게시판에 설정된 이미지폭을 초과한다면 lightbox를 사용
if ($size[0] > $board['bo_image_width'])
return "<a rel='lightbox' href='$img_file'><img src='$img_file' width='{$board['bo_image_width']}' alt='lightbox' /></a>";
else
return "<img src='$img_file' alt='$content' />";
}
/* 110106 : FLASH XSS 공격으로 인하여 코드 자체를 막음
else if (preg_match("/\.($config['cf_flash_extension'])$/i", $file))
//return "<embed src='{$g4['path']}/data/file/{$board['bo_table']}/$file' $attr></embed>";
return "<script>doc_write(flash_movie('{$g4['path']}/data/file/{$board['bo_table']}/$file', '_g4_{$ids}', '$width', '$height', 'transparent'));</script>";
//=============================================================================================
// 동영상 파일에 악성코드를 심는 경우를 방지하기 위해 경로를 노출하지 않음
//---------------------------------------------------------------------------------------------
else if (preg_match("/\.($config['cf_movie_extension'])$/i", $file))
//return "<embed src='{$g4['path']}/data/file/{$board['bo_table']}/$file' $attr></embed>";
return "<script>doc_write(obj_movie('{$g4['path']}/data/file/{$board['bo_table']}/$file', '_g4_{$ids}', '$width', '$height'));</script>";
//=============================================================================================
*/
}
// view_file_link() 함수에서 넘겨진 이미지를 보이게 합니다.
// {img:0} ... {img:n} 과 같은 형식
function view_image($view, $number, $attribute)
{
if ($view['file'][$number]['view'])
return preg_replace("/>$/", " $attribute>", $view['file'][$number]['view']);
else
//return "{".$number."번 이미지 없음}";
return "";
}
/*
// {link:0} ... {link:n} 과 같은 형식
function view_link($view, $number, $attribute)
{
global $config;
if ($view['link'][$number]['link'])
{